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)
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.
An empty file is a file of zero bytes size. An empty directory is a directory that doesn't contain any file or directory. It's fair to say that empty files don't consume space, but we should clean our file system from time to time as a best practice.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With