Click to See Complete Forum and Search --> : Bug in FSTREAM


quantass
January 28th, 2003, 02:58 AM
I'm creating an instance of the IFSTREAM class (ifstream myFile). I'm able to open and read from the file the object is connected to. However after closing the object and then trying to Open again I promptly get an error.

My code looks something like this:
===
ifstream inFile;

inFile.open("e:\\Test.exe", ios::binary);
if (!inFile)
{cout << "File Open Error - Read" << endl; return 0;}
.
.
.
inFile.close();
inFile.open("e:\\Test2.exe", ios::binary);
if (!inFile)
{cout << "File Open Error - Read2" << endl; return 0;}
===

The error occurs for the second if (!inFile). Is this a bug within Visual C++'s implementation of ifstream? When i alter the ifstream object to a pointer (ie. ifstream *inFile) and apply new/delete before the next open all is fine. Why??

Philip Nicoletti
January 28th, 2003, 05:35 AM
This is not a bug. closing and opening a stream does
not clear its state. Either after closing (or before
trying to open), you need to clear the state:



inFile.clear();


See Section 13.9.1 of "The C++ Standard Library" by
Josuttis if you have it.