Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: .eof on an empty file

Tags:

c++

eof

fstream

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);
like image 947
Mohamed Ahmed Nabil Avatar asked Dec 21 '22 17:12

Mohamed Ahmed Nabil


2 Answers

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

like image 170
Yippie-Ki-Yay Avatar answered Dec 24 '22 01:12

Yippie-Ki-Yay


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.

like image 25
CB Bailey Avatar answered Dec 24 '22 02:12

CB Bailey