There's actually a small degree of implementation dependency as
to when the eofbit
is set. (The function eof()
returns true
if and only if the eofbit
is set.) It is required to be set
if, in the course of reading something (formatted or
unformatted), a call to streambuf::sgetc()
(or one of the
other character getters) returns std::char_traits::eof()
.
It's not always clear when the implementation may look one
character ahead—if it gets an end of file doing so, it
sets eofbit
; if it doesn't do the look-ahead, it doesn't.
I'm also unsure as to whether an implementation can set eofbit
in cases where it knows that the next read must return eof
,
without actually having done the read; I'm fairly sure that
existing implementations don't, however. (Do you really want
the eofbit
set when you seek to the end of file?) So in your
example, you will almost surely never see eof()
returning
true.
All of this explains why you almost never do input.eof()
(or
input.good()
, which includes the eofbit
in its value as
well). After trying to open the file, the usual condition is
if ( input.is_open() )
, although input.fail()
can be used as
well. When reading an already opened file, we test
input.fail()
after the attempted input, usually by using the
stream object in a boolean context (i.e. if ( input )
, or if
( !input )
). After having detected failure, we may use
eof()
to determine whether the reason for failure was the end
of file, or some other error (like "abc"
when trying to input
an int
). Even then, it's not 100% infallible, and eof()
may
return true even if there was an error in the format.
(Consider:
std::istringstream s( "1.3E+" );
double d;
s >> d;
In this case, s.eof()
will almost certainly return true,
dispite the fact that the input fails because of an error in the
format, and not because of end of file.)