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

5
我试图使用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
}

使用这种方法无法检测到任何空文件。如果我使用 inputFile.peek 而不是 eof,那么它会将我的好文件误判为空文件。


你是如何使用 peek() 的?顺便说一下,EOF标志仅在读取到文件末尾后设置。 - Ry-
糟糕,我再次错过了这个重复的问题。如今几乎没有一个问题是完全没有任何形式的重复的。 - P0W
4个回答

14

使用 peek 的方式如下

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

}

3

我会在文件结尾打开并使用tellg()查看该位置:

std::ifstream ifs("myfile", std::ios::ate); // std::ios::ate means open at end

if(ifs.tellg() == 0)
{
    // file is empty
}

函数tellg()返回文件的读取(获取)位置,我们使用std::ios::ate打开文件并将读取(获取)位置设置为末尾。因此,如果tellg()返回0,则文件为空。

更新:C++17开始,您可以使用std::filesystem::file_size

#include <filesystem>

namespace fs = std::filesystem; // for readability

// ...

if(fs::file_size(myfile) == 0)
{
    // file is empty
}

注意: 一些编译器已经将 <filesystem> 库作为技术规范支持(例如,GCC v5.3)。


2
如果“空”意味着文件长度为零(即根本没有字符),那么只需找到文件的长度并查看它是否为零:
inputFile.seekg (0, is.end);
int length = is.tellg();

if (length == 0)
{
    // do your error handling
}

0
ifstream fin("test.txt");
if (inputFile.fail()) //check for file open failure
{
    cout << "Error opening file" << endl;
    cout << "Note that the program will halt" << endl;//error prompt
}
int flag=0;
while(!fin.eof())
{
char ch=(char)fin.get();
flag++;
break;
}
if (flag>0)
cout << "File is not empty" << endl;
else
cout << "File is empty" << endl;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接