Lets see this program:
ifstream filein("hey.txt");
if(filein.eof()){
cout<<"END"<<endl;
}
Here "hey.txt" is empty. So the if condition here is thought should have been true But it isnt
Why isnt the eof returning true although the file is empty?
If i added this before the if
the eof returns true although arr
is still empty and the file is still empty so both unchanged
char arr[100];
filein.getline(arr,99);
eof()
function returns "true" after the program attempts to read past the end of the file.
You can use std::ifstream::peek()
to check for the "logical end-of-file".
The flag std::ios_base::eofbit
is set when reaching the end of a stream while trying to read. Until an attempt is made to read past the end of a stream this flag won't be set.
In general, use of std::ios_base::eofbit
is rather limited. The only reasonable use is for suppressing an error after a failed read: It is normally not an error if a read failed due to reaching end of file. Trying to use this flag for anything else won't work.
eof()
tests whether the "end of file" flag is set on the C++ stream object. This flag is set when a read operation encouters the end of the input from the underlying device (file, standard input, pipe, etc.). Before you attempt a read on an empty file the flag is not set. You have to perform an operation that will try to read something before the flag will be set on the stream object.