Must always use clear() after reaching eof?

Aug 17, 2008 at 3:39am
I was having problems trying to get a filestream to continue working after I had already reached the end of the file from a previous operation. I tried to set the stream pointer to ::beg, and I tried to close and open the stream again, but the stream still wouldn't work. I found that by using clear(), the stream began to function again.

If it is true that you must use clear() after every eof, then I think a note about that really needs to be included in the i/o tutorial because there is at least one example code that uses a "while (! myfile.eof())" , meaning that the practice of reading until eof is being taught without any warning given.

Or am I missing something?
Aug 17, 2008 at 1:45pm
No, you are exactly right.

File operations should always code against all stop conditions, so
while (!myfile.eof())
is bad, because it can introduce an infinite loop. It is better to say
while (myfile.good())
or just
while (myfile)
and test why it stopped (eof, bad, fail) afterwards.

Any time one of those stop bits gets set, no further I/O can be done on the stream until clear() is called --that is, until the stop bits are cleared.

Hope this helps.
Aug 17, 2008 at 5:10pm
Yeah, thanks. I'll use "while (myfile.good())" from now on.

I'll send a note to the tuts author.
Topic archived. No new replies allowed.