【问题标题】:How to detect an empty file in C++? [duplicate]如何在 C++ 中检测空文件? [复制]
【发布时间】:2014-10-07 04:11:37
【问题描述】:

我正在尝试使用 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 标志仅在读取到达文件末尾后设置。
  • 哎呀,又错过了这个副本,这些天几乎没有任何问题,没有任何重复的方式

标签: c++ error-handling fstream


【解决方案1】:

使用peek,如下所示

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

}

【讨论】:

    【解决方案2】:

    我会在最后打开文件,看看那个位置使用的是什么tellg()

    std::ifstream ifs("myfile", std::ios::ate); // std::ios::ate means open at end
    
    if(ifs.tellg() == 0)
    {
        // file is empty
    }
    

    函数tellg()返回文件的读取(get)位置,我们使用std::ios::ate打开文件,读取(get)位置在末尾。所以如果tellg() 返回0 它一定是空的。

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

    #include <filesystem>
    
    namespace fs = std::filesystem; // for readability
    
    // ...
    
    if(fs::file_size(myfile) == 0)
    {
        // file is empty
    }
    

    注意:一些编译器已经支持&lt;filesystem&gt; 库作为Technical Specification(例如,GCC v5.3)。

    【讨论】:

      【解决方案3】:

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

      inputFile.seekg (0, is.end);
      int length = is.tellg();
      
      if (length == 0)
      {
          // do your error handling
      }
      

      【讨论】:

        【解决方案4】:
        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;
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2019-05-09
          • 1970-01-01
          • 1970-01-01
          • 2011-11-30
          • 2012-04-09
          • 2020-07-26
          • 2010-09-06
          • 2015-06-07
          相关资源
          最近更新 更多