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.
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.
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.
Use peek
like following
if ( inputFile.peek() == std::ifstream::traits_type::eof() )
{
// Empty File
}
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).
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