在C ++中检查空文件

时间:2010-03-06 00:48:35

标签: c++ eof

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

编辑,我尝试使用fseek方法,但是我收到一条错误,上面写着“无法将ifstream转换为FILE *”。

我的功能参数是

myFunction(ifstream &inFile)

9 个答案:

答案 0 :(得分:64)

也许类似于:

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

答案 1 :(得分:8)

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

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

答案 2 :(得分: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功能并直接检查文件大小。

答案 3 :(得分:1)

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

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

答案 4 :(得分:1)

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

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

答案 5 :(得分:0)

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

fclose(pFile)

答案 6 :(得分: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;
}

答案 7 :(得分:0)

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 对象中提取文件路径。

答案 8 :(得分:-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;
}
相关问题