How do I detect an empty file in C ++?
I'm trying to use eof and peek, but both don't seem to give me the correct 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 an empty file using this method. If I use inputFile.peek instead of eof it makes my nice files empty.
source to share
I would open the file at the end and see what this 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 from the read (get) position at the end using std::ios::ate
. Therefore, if it tellg()
returns 0
, it must be empty.
Update: From C++17
below 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 library <filesystem>
as a Technical Specification (eg GCC v5. 3).
source to share
ifstream fin("test.txt");
if (inputFile.fail()) //check for file open failure
{
cout << "Error opening file" << endl;
cout << "Note that the program will halt" << endl;//error prompt
}
int flag=0;
while(!fin.eof())
{
char ch=(char)fin.get();
flag++;
break;
}
if (flag>0)
cout << "File is not empty" << endl;
else
cout << "File is empty" << endl;
source to share