VS8 can't handle file.close(); file.open();, why?
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.
上一篇: 请参阅Scala反射中的注释