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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26228424/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 11:33:24  来源:igfitidea点击:

How to detect an empty file in C++?

c++error-handlingfstream

提问by zhang zhengchi

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

我正在尝试使用 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
}

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.

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

回答by P0W

Use peeklike following

使用peek如下

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

}

回答by Galik

I would open the file at the end and see what that position is using tellg():

我会在最后打开文件并查看该位置正在使用的内容tellg()

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

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

The function tellg()returns the read (get) position of the file and we opened the file with the read (get) position at the end using std::ios::ate. So if tellg()returns 0it must be empty.

该函数tellg()返回文件的读取(获取)位置,我们使用std::ios::ate. 所以如果tellg()返回0它必须是空的。

Update:From C++17onward you can use std::filesyatem::file_size:

更新:C++17以后你可以使用std::filesytem::file_size

#include <filesystem>

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

// ...

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

Note:Some compilers already support the <filesystem>library as a Technical Specification(eg, GCC v5.3).

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

回答by Adam

If "empty" means that the length of the file is zero (i.e. no characters at all) then just find the length of the file and see if it's zero:

如果“空”意味着文件的长度为零(即根本没有字符),那么只需找到文件的长度并查看它是否为零:

inputFile.seekg (0, is.end);
int length = is.tellg();

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

回答by Vikramjeet

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;