49

有没有一种简单的方法来检查文件是否为空。就像你将一个文件传递给一个函数并且你意识到它是空的,然后你马上关闭它?谢谢。

编辑,我尝试使用 fseek 方法,但我收到一条错误消息,提示“无法将 ifstream 转换为 FILE *”。

我的函数的参数是

myFunction(ifstream &inFile)
4

10 回答 10

85

也许类似于:

bool is_empty(std::ifstream& pFile)
{
    return pFile.peek() == std::ifstream::traits_type::eof();
}

短而甜。


考虑到您的错误,其他答案使用 C 样式的文件访问,您可以在其中获得FILE*特定功能。

相反,你和我正在使用 C++ 流,因此不能使用这些函数。上面的代码以一种简单的方式工作:peek()将查看流并返回而不删除下一个字符。如果到达文件末尾,则返回eof(). 因此,我们只是peek()在流中查看它是否是eof(),因为空文件没有什么可看的。

请注意,如果文件从未打开过,这也会返回 true,这应该适用于您的情况。如果你不想这样:

std::ifstream file("filename");

if (!file)
{
    // file is not open
}

if (is_empty(file))
{
    // file is empty
}

// file is open and not empty
于 2010-03-06T00:56:35.767 回答
10

好的,所以这段代码应该适合你。我更改了名称以匹配您的参数。

inFile.seekg(0, ios::end);  
if (inFile.tellg() == 0) {    
  // ...do something with empty file...  
}
于 2010-03-06T00:54:13.077 回答
5

查找文件末尾并检查位置:

 fseek(fileDescriptor, 0, SEEK_END);
 if (ftell(fileDescriptor) == 0) {
     // file is empty...
 } else {
     // file is not empty, go back to the beginning:
     fseek(fileDescriptor, 0, SEEK_SET);
 }

如果您还没有打开文件,只需使用该fstat功能并直接检查文件大小。

于 2010-03-06T00:51:30.080 回答
1
char ch;
FILE *f = fopen("file.txt", "r");

if(fscanf(f,"%c",&ch)==EOF)
{
    printf("File is Empty");
}
fclose(f);
于 2015-01-19T17:19:09.360 回答
1

使用这个: data.peek() != '\0'

我一直在寻找一个小时,直到最后这有帮助!

于 2018-01-21T16:36:18.400 回答
1

C++17解决方案:

#include <filesystem>

const auto filepath = <path to file> (as a std::string or std::filesystem::path)

auto isEmpty = (std::filesystem::file_size(filepath) == 0);

假设您存储了文件路径位置,我认为您不能从std::ifstream对象中提取文件路径。

于 2021-01-28T19:10:43.183 回答
0
pFile = fopen("file", "r");
fseek (pFile, 0, SEEK_END);
size=ftell (pFile);
if (size) {
  fseek(pFile, 0, SEEK_SET);
  do something...
}

fclose(pFile)
于 2010-03-06T00:53:27.773 回答
0

怎么样(虽然不是优雅的方式)

int main( int argc, char* argv[] )
{
    std::ifstream file;
    file.open("example.txt");

    bool isEmpty(true);
    std::string line;

    while( file >> line ) 
        isEmpty = false;

        std::cout << isEmpty << std::endl;
}
于 2015-01-19T17:38:36.907 回答
0

当文件为空时,如果它为空,tellg 将为您提供值 0,因此请专注于此,这是查找空文件的最简单方法,如果您只是创建文件,它将为您提供 -1。

outfile.seekg(0,ios::end);
if(file.tellg()<1){
  //empty
}else{
  file.clear(); // clear all flags(eof)
  file.seekg(0,ios::beg);//reset to front
  //not empty
}
于 2021-10-28T14:24:23.503 回答
-1
if (nfile.eof()) // Prompt data from the Priming read:
    nfile >> CODE >> QTY >> PRICE;
else
{
    /*used to check that the file is not empty*/
    ofile << "empty file!!" << endl;
    return 1;
}
于 2016-11-04T11:04:21.680 回答