49

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.

Edit, I tried using the fseek method, but I get an error saying 'cannot convert ifstream to FILE *'.

My function's parameter is

myFunction(ifstream &inFile)
Crystal
  • 27,012
  • 59
  • 215
  • 378
  • It's too bad that you can't easily get a file descriptor from an `fstream`. You can easily enough check for an empty file using `fstat`, on Unix. :-P – Chris Jester-Young Mar 06 '10 at 01:43

10 Answers10

86

Perhaps something akin to:

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

Short and sweet.


With concerns to your error, the other answers use C-style file access, where you get a FILE* with specific functions.

Contrarily, you and I are working with C++ streams, and as such cannot use those functions. The above code works in a simple manner: peek() will peek at the stream and return, without removing, the next character. If it reaches the end of file, it returns eof(). Ergo, we just peek() at the stream and see if it's eof(), since an empty file has nothing to peek at.

Note, this also returns true if the file never opened in the first place, which should work in your case. If you don't want that:

std::ifstream file("filename");

if (!file)
{
    // file is not open
}

if (is_empty(file))
{
    // file is empty
}

// file is open and not empty
GManNickG
  • 478,574
  • 51
  • 478
  • 539
10

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...  
}
pajton
  • 15,360
  • 7
  • 53
  • 65
  • so what exactly is this doing ? it works but I want to know why. is it checking the end of the stream and seeing if its equal to 0? –  Feb 16 '21 at 06:07
5

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.

mmx
  • 402,675
  • 87
  • 836
  • 780
1
char ch;
FILE *f = fopen("file.txt", "r");

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

use this: data.peek() != '\0'

I've been searching for an hour until finaly this helped!

Vytaute
  • 11
  • 1
1

C++17 solution:

#include <filesystem>

const auto filepath = <path to file> (as a std::string or std::filesystem::path)

auto isEmpty = (std::filesystem::file_size(filepath) == 0);

Assumes you have the filepath location stored, I don't think you can extract a filepath from an std::ifstream object.

Mansoor
  • 2,306
  • 1
  • 15
  • 26
0
pFile = fopen("file", "r");
fseek (pFile, 0, SEEK_END);
size=ftell (pFile);
if (size) {
  fseek(pFile, 0, SEEK_SET);
  do something...
}

fclose(pFile)
sizzzzlerz
  • 4,101
  • 3
  • 22
  • 34
0

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;
}
CroCo
  • 5,358
  • 7
  • 50
  • 79
  • 1
    Fair enough. It's slightly better (due to being _actual_ C++, not C) than user4471014's, though still entirely wasteful and suboptimal. – Lightness Races in Orbit Jan 19 '15 at 17:52
  • @LightnessRacesinOrbit, you are right, however no need for going through all lines of a file. The while loop could be stopped once the first line is being detected and set `isEmpty` to `false`. If that could enhance the code. – CroCo Jan 19 '15 at 17:59
  • I can understand this code is suboptimal but why it is wasteful? The OP is not asking or looking for sufficient or so optimized code. – CroCo Jan 19 '15 at 18:08
  • (a) It's wasteful because you're extracting data that you are never going to use. Reading those characters was pointless. (b) Just because the OP didn't go out of their way to ask for "optimized" code doesn't mean we should go out of our way to provide the opposite. :) – Lightness Races in Orbit Jan 20 '15 at 13:48
0

when the file is empty the tellg will give you value 0 if its empty so focus on that and it is the simplest way to find an empty file, if you just create the file it will give you -1.

outfile.seekg(0,ios::end);
if(file.tellg()<1){
  //empty
}else{
  file.clear(); // clear all flags(eof)
  file.seekg(0,ios::beg);//reset to front
  //not empty
}
Aylian Craspa
  • 342
  • 3
  • 11
-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;
}
amna
  • 1