Search code examples
c++error-handlingfstream

How to detect an empty file in C++?


I am trying to use eof and peek but both seems not to give me the right answer.

if (inputFile.fail()) //check for file open failure
{
    cout << "Error opening file" << endl;
    cout << "Note that the program will halt" << endl;//error prompt
}

else if (inputFile.eof())
{
    cout << "File is empty" << endl;
    cout << "Note that program will halt" << endl; // error prompt
}
else
{
    //run the file
}

it cannot detect any empty file using this method. If i use inputFile.peek instead of eof it would make my good files as empty files.


Solution

  • Use peek like following

    if ( inputFile.peek() == std::ifstream::traits_type::eof() )
    {
       // Empty File
    
    }