如何在C++中检测空文件?

zha*_*chi 3 c++ error-handling fstream

我正在尝试使用eof和peek,但两者似乎都没有给我正确的答案.

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
}
Run Code Online (Sandbox Code Playgroud)

它使用此方法无法检测到任何空文件.如果我使用inputFile.peek而不是eof,它会将我的好文件作为空文件.

P0W*_*P0W 8

使用peek如下

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

}
Run Code Online (Sandbox Code Playgroud)