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.