4

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);
Mohamed Ahmed Nabil
  • 3,949
  • 8
  • 36
  • 49
  • @uberwulu: "...it reads the EOF character." - what EOF character? shells / command-prompts use a character to allow a user at a keyboard to denote end-of-file, but in every modern OS I know files do not actually embed EOF characters... EOF is a state set when there is nothing to read. – Tony Delroy Aug 27 '12 at 01:00

3 Answers3

5

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".

Yippie-Ki-Yay
  • 22,026
  • 26
  • 90
  • 148
4

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.

CB Bailey
  • 755,051
  • 104
  • 632
  • 656
3

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.

Dietmar Kühl
  • 150,225
  • 13
  • 225
  • 380