I've got, probably trivial question but i can't understand it. I've wrote the simple code:
fstream file;
file.open("data", ios::in);
if(!file.good()){
file.close();
file.open("data", ios::out);
if(!file.good()) cout<<"not good"<<endl;
file<<"test"<<endl;
file.close();
}
in fresh VS8 C++ Express project. When I run it and "data" doesn't exists, it creates file, but also returns "not good"(the second one) so the output is not written in file. And now comes the funny thing. If I compile same code in VS10 C++ Express and Code::Blocks 12, it works fine.
Why is it so?
@edit My friend checked it on his PC with VS8 C++ Expres too. Works same for him.
@edit2 Same as my comment with "solution":
Forcing to clear failbit with .clear(); method seems to work. It hurts when you learn in newer IDE and then has to switch to older one :/. Tho, it gives nice lesson. Thanks guys.
This was by design. In C++98, closing an fstream does not clear the error state and calling open()
on an fstream does not reset the error state. See LWG Defect #409 for a discussion of the issue.
The behavior was changed in C++11 such that the error state is cleared (via a call to clear()
) if the open operation succeeds.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With