Checking for an empty file in C++

前端 未结 8 1984
抹茶落季
抹茶落季 2020-11-27 03:35

Is there an easy way to check if a file is empty. Like if you are passing a file to a function and you realize it\'s empty, then you close it right away? Thanks.

E

相关标签:
8条回答
  • 2020-11-27 03:47
    char ch;
    FILE *f = fopen("file.txt", "r");
    
    if(fscanf(f,"%c",&ch)==EOF)
    {
        printf("File is Empty");
    }
    fclose(f);
    
    0 讨论(0)
  • 2020-11-27 03:52

    How about (not elegant way though )

    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;
    }
    
    0 讨论(0)
  • 2020-11-27 03:57
    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;
    }
    
    0 讨论(0)
  • 2020-11-27 03:58

    Ok, so this piece of code should work for you. I changed the names to match your parameter.

    inFile.seekg(0, ios::end);  
    if (inFile.tellg() == 0) {    
      // ...do something with empty file...  
    }
    
    0 讨论(0)
  • 2020-11-27 03:59
    pFile = fopen("file", "r");
    fseek (pFile, 0, SEEK_END);
    size=ftell (pFile);
    if (size) {
      fseek(pFile, 0, SEEK_SET);
      do something...
    }
    
    fclose(pFile)
    
    0 讨论(0)
  • 2020-11-27 04:00

    Seek to the end of the file and check the position:

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

    If you don't have the file open already, just use the fstat function and check the file size directly.

    0 讨论(0)
提交回复
热议问题