Resetting an ifstreams error flags

CodeX

2[H]4U
Joined
Mar 21, 2006
Messages
2,879
Okay, so I loop through a file like this:

while(file->good()) {...}

good() returns true if none of the ifstreams error flags are set. Now, assume that that loop is inside a larger loop so that I am reading the entire file multiple times in succession. First I would obviously have to set the get pointer back to the beginning of the file, but I would also need to clear the error flags. If you don't do this good() will immediately evaluate to false because the eof (end of file) flag is still set from the previous iteration.

Now, I have tried multiple ways to clear these error flags and the only way that I have come up with that works is to delete the ifstream object and create a new one every time I want re-read the file, which is obviously not optimal.

I have tried using clear() but that just does not work, at least it is not working as I would expect it to...
 
What isn't clear() resetting, just the eof flag? Have you tried manually going back to the beginning of the file with something like seekg(0, ios::beg)?
 
What isn't clear() resetting, just the eof flag? Have you tried manually going back to the beginning of the file with something like seekg(0, ios::beg)?

yeah, you have to do that anyways, but the eof flag remains set so it won't go into the loop again. According to the documentation clear() should set all 3 error flags to 0, but after calling it at least one of them is still set, since good() continues to evaluate false. I suppose I could use rdstate() to find out exactly which ones are set, I just assume that it is eof.
 
So is this something like what you're trying to do?

Code:
int main( )
{
	ifstream in ;
	string line ;
	in.open( "test.txt" ) ;

	for( int i = 0 ; i < 2 ; ++i )
	{
		while( in.good( ) )
		{
			in >> line ;
			cout << line << endl ;
		}
		in.clear( ) ;
		in.seekg( 0, ios::beg ) ;
		cout << endl << endl ;
	}

	in.close( ) ;
	system( "PAUSE" ) ;
	return 0 ;
}

For me I get the output (which is correct):
Code:
line1
line2
line3


line1
line2
line3
 
So is this something like what you're trying to do?

yeah... I tried it again and it worked... must have been another problem that I didn't even see and I assumed it was that, the debug trace did exactly what I said though, ran through the file once, came back up for the second run of the loop, and then file->good() failed so it fell through and quit. Guess I'll never know what the real problem was because it works now... thanks.
 
Back
Top