Quote:
> Which part detects the end of file?
> for ( i = 0 ; i < ITEMS && fin ; i++ )
This part. As you can see, the for loop continues as long as 'i < ITEMS &&
fin'. To evaluate fin as a boolean expression (true or false), it needs to
convert it to a number. The function that does that is basic_ios::operator
void*() (basic_ios is a base class of basic_ifstream, of which ifstream is a
special case for files with char data).
From the documentation of basic_ios::operator void*():
"The operator returns a null pointer only if fail."
See also:
ms-help://MS.VSCC/MS.MSDNVS/vcstdlib/html/vclrfbasiciosoperatorvoidasterisk.
htm
In other words, if the stream is bad (ie, cannot be read anymore), this
conversion yields NULL (0), which is equivalent to false in C++, so the loop
terminates.
Note that this method terminates the loop in any condition where the stream
can't be read anymore. This may indicate eof, but it may also indicate some
kind of error. To determine which of the two occurred, use the function
basic_ios::eof(), like this:
int i;
ifstream fin("Test.txt");
/* The for loop above is nice, but necessary only if you want to read the
stream till the end or up to a specific amount of data. If you just want to
read the stream until the end, use a while loop. Note that the if( !fin ) is
also not necessary, since the while loop won't execute if fin.operator void*
returns 0. The same would be true with the for loop by the way */
while( fin )
{
// Read the stream.
Quote:
}
if( fin.eof() ) // successfully read the whole stream
return true;
else // some error occurred
return false;
--
Sven Groot