在C ++中检查空文件

问题描述 投票:38回答:8

是否有一种简单的方法来检查文件是否为空。就像如果您将文件传递给函数并且意识到它是空的,那么立即关闭它吗?谢谢。

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

我的函数的参数是

myFunction(ifstream &inFile)
c++ eof
8个回答
71
投票

也许类似于:

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

8
投票

好,所以这段代码应该对您有用。我更改了名称以匹配您的参数。

inFile.seekg(0, ios::end);  
if (inFile.tellg() == 0) {    
  // ...do something with empty file...  
}

6
投票

搜索文件末尾并检查位置:

 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功能并直接检查文件大小。


1
投票
char ch;
FILE *f = fopen("file.txt", "r");

if(fscanf(f,"%c",&ch)==EOF)
{
    printf("File is Empty");
}
fclose(f);

1
投票

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

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


0
投票
pFile = fopen("file", "r");
fseek (pFile, 0, SEEK_END);
size=ftell (pFile);
if (size) {
  fseek(pFile, 0, SEEK_SET);
  do something...
}

fclose(pFile)

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;
}

-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;
}
© www.soinside.com 2019 - 2024. All rights reserved.