Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking for an empty file in C++

Tags:

c++

eof

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) 
like image 461
Crystal Avatar asked Mar 06 '10 00:03

Crystal


People also ask

How do you check if the file is empty in CPP?

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.

What is file empty?

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.


1 Answers

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 
like image 192
GManNickG Avatar answered Sep 19 '22 23:09

GManNickG