One idea about using ofstream

Source: Internet
Author: User

The following code snippet is available:

Ofstream OFS;
While (...)
{
OFS. Close ();
OFS. Open (...)
OFS <"content ";
...
}
OFS. Close ();

You can also find that close is called once before the first open. The result is that the output file is created, but nothing is written as expected.

Cause: When close is called for the first time, an error mark is generated, leading to write failure. The result of calling the relevant function Detection Status is:
Is_open (); // true
EOF (); // false
Bad (); // false
Fail (); // true
Good (); // false

Calling close incorrectly does not cause any exceptions, but the code has potential risks. This error cannot be detected only when is_open () or bad () is used.. In fact, it is also valid to call clear after the first call of close, but the code should not be written like this.

Conclusion:
1. Be cautious when calling the close function of fstrea. before calling the function, use is_open to check whether the function is opened, and then decide whether to call close;
2. After opening a file, besides calling is_open to check the open status, you should also use good to further determine whether the file stream is in normal state.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.