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.

+3


source to share


4 answers


Use peek

as below



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

}

      

+6


source


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).

+2


source


If empty means the length of the file is zero (ie no characters at all), just find the length of the file and see if it is:

inputFile.seekg (0, is.end);
int length = is.tellg();

if (length == 0)
{
    // do your error handling
}

      

+2


source


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;

      

0


source







All Articles