Crystal Crystal - 2 months ago 46
C++ Question

Checking for an empty file in C++

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)


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