代码之家  ›  专栏  ›  技术社区  ›  Crystal

在C++中检查一个空文件[复制]

  •  36
  • Crystal  · 技术社区  · 15 年前

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

    编辑,我尝试使用fseek方法,但我得到一个错误,说“无法将ifstream转换为文件*”。

    我函数的参数是

    myFunction(ifstream &inFile)
    
    8 回复  |  直到 7 年前
        1
  •  59
  •   GManNickG    15 年前

    可能类似于:

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

    又矮又甜。


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

    相反,您和我正在使用C++流,因此不能使用这些函数。上述代码的工作方式很简单: peek() 将偷看流并返回下一个字符,而不删除。如果到达文件结尾,则返回 eof() .因此,我们只是 PEEK() 在小溪边,看看是不是 Ef() ,因为空文件没有可查看的内容。

    注意,如果文件从来没有在第一时间打开过,这也会返回true,在您的情况下应该是这样的。如果你不想要:

    std::ifstream file("filename");
    
    if (!file)
    {
        // file is not open
    }
    
    if (is_empty(file))
    {
        // file is empty
    }
    
    // file is open and not empty
    
        2
  •  8
  •   pajton    15 年前

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

    inFile.seekg(0, ios::end);  
    if (inFile.tellg() == 0) {    
      // ...do something with empty file...  
    }
    
        3
  •  5
  •   Mehrdad Afshari    15 年前

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

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

        4
  •  1
  •   user4471014    10 年前
    char ch;
    FILE *f = fopen("file.txt", "r");
    
    if(fscanf(f,"%c",&ch)==EOF)
    {
        printf("File is Empty");
    }
    fclose(f);
    
        5
  •  1
  •   Vytaute    7 年前

    使用此: 数据!=‘0’

    我已经找了一个小时了,终于有了帮助!

        6
  •  0
  •   sizzzzlerz    15 年前
    pFile = fopen("file", "r");
    fseek (pFile, 0, SEEK_END);
    size=ftell (pFile);
    if (size) {
      fseek(pFile, 0, SEEK_SET);
      do something...
    }
    
    fclose(pFile)
    
        7
  •  0
  •   CroCo    10 年前

    怎么样(虽然不是很优雅)

    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;
    }
    
        8
  •  -1
  •   amna    9 年前
    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;
    }