Re: eof() is there a better way
From: Chris \( Val \) (chrisval_at_bigpond.com.au)
Date: 03/30/04
- Next message: Chris \( Val \): "Re: returning objects"
- Previous message: osmium: "Re: returning objects"
- In reply to: Satan: "eof() is there a better way"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: Tue, 30 Mar 2004 22:42:00 +1000
"Satan hotmail.com>" <q9722390<NoSpam@> wrote in message
news:40692688$0$16588$5a62ac22@freenews.iinet.net.au...
| Hi,
|
| I am always having trouble with the following:
|
| while ( !read_file.eof()){
| // do something
| }
I'm sure you are, because 'eof()' only becomes true,
when you have read past it, but by then it is too late,
and you will often end up reading the last line twice
in an expression such as the above.
| Looping again when i think the file should be empty.
| It even loops when i have created a new file with
| nothing in it (editor - vi).
|
| Is there a better way to ensure you are at EOF ?
Sure there is - The following will read until 'eof()'
is reached, and then terminate:
The correct idiom to use is:
// Meaning while 'true' in an boolean context...
while( "there is data" )
...do something
Which would evaluate to:
while( read_file.getline( buffer... ) )
// do something
while( read_file >> buffer )
// do something
while( std::getline( read_file, buffer ) )
// do something
After the while loop has completed, it is good practice
to explicitly check that the file was indeed read to the
end:
if( read_file.eof() )
// The whole file was successfully read to 'eof()'.
Cheers.
Chris Val
- Next message: Chris \( Val \): "Re: returning objects"
- Previous message: osmium: "Re: returning objects"
- In reply to: Satan: "eof() is there a better way"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|