VS8 cannot handle file.close (); file.open () ;, why?

I probably have a trivial question, but I can’t understand this. I wrote a 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 the new VS8 C ++ Express project. When I run it and the β€œdata” does not exist, it creates a file, but also returns β€œnot good” (second), so the output is not written to the file. And now comes the fun thing. If I compile the same code in VS10 C ++ Express and Code :: Blocks 12, it works fine.

Why is this so?

@edit My friend tested it on his PC using VS8 C ++ Expres. He works for him.

@ edit2 Same as my comment with "solution":

Forcing a failbit reset with .clear (); the way seems to work. It hurts when you study in the new IDE and then switch to the older one: /. Tho, this gives a good lesson. Thanks guys.

+7
source share
1 answer

It was by design. In C ++ 98, closing fstream does not clear the error state, and calling open() on fstream does not mean resetting the error state. See LWG Defect # 409 for a discussion of the issue.

The behavior has been changed to C ++ 11, so the error state is cleared (when clear() called) if the open operation completes successfully.

+4
source

All Articles