Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect an empty file in C++? [duplicate]

I am trying to use eof and peek but both seems not to give me the right answer.

if (inputFile.fail()) //check for file open failure
{
    cout << "Error opening file" << endl;
    cout << "Note that the program will halt" << endl;//error prompt
}

else if (inputFile.eof())
{
    cout << "File is empty" << endl;
    cout << "Note that program will halt" << endl; // error prompt
}
else
{
    //run the file
}

it cannot detect any empty file using this method. If i use inputFile.peek instead of eof it would make my good files as empty files.

like image 450
zhang zhengchi Avatar asked Oct 07 '14 04:10

zhang zhengchi


People also ask

How do you check if it is an empty file in C?

So you could use feof() to check if fp reaches end of file. Or fgetc() and check for EOF. If size is ever 0, you know the file is empty.

How check file is empty or not in C++?

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.


2 Answers

Use peek like following

if ( inputFile.peek() == std::ifstream::traits_type::eof() )
{
   // Empty File

}
like image 108
P0W Avatar answered Sep 30 '22 17:09

P0W


I would open the file at the end and see what that position is using tellg():

std::ifstream ifs("myfile", std::ios::ate); // std::ios::ate means open at end

if(ifs.tellg() == 0)
{
    // file is empty
}

The function tellg() returns the read (get) position of the file and we opened the file with the read (get) position at the end using std::ios::ate. So if tellg() returns 0 it must be empty.

Update: From C++17 onward you can use std::filesyatem::file_size:

#include <filesystem>

namespace fs = std::filesystem; // for readability

// ...

if(fs::file_size(myfile) == 0)
{
    // file is empty
}

Note: Some compilers already support the <filesystem> library as a Technical Specification (eg, GCC v5.3).

like image 39
Galik Avatar answered Sep 30 '22 16:09

Galik