In a separate function, create a variable, increment it every time a line is found (getline()). Then return the amount of lines counted. If its 0, then search the line for characters. If none are found you have a blank file.
int length;
ifstream filestr;
filestr.open("fileYouWantToTest.txt", ios::binary); // open your file
filestr.seekg(0, ios::end); // put the "cursor" at the end of the file
length = filestr.tellg(); // find the position of the cursor
filestr.close(); // close your file
if ( length == 0 ){...}
else {...}
[edit] Note: length is the number of characters/bytes in the file
#include <ciso646>
#include <fstream>
#include <iostream>
#include <string>
usingnamespace std;
//----------------------------------------------------------------------------
bool is_textfile_empty( constchar* filename )
{
string s;
ifstream f( filename, ios::binary );
// Check for UTF-8 BOM
if (f.peek() == 0xEF)
{
f.get();
if (f.get() != 0xBB) returnfalse;
if (f.get() != 0xBF) returnfalse;
}
// Scan every line of the file for non-whitespace characters
while (getline( f, s ))
{
if (s.find_first_not_of(
" \t\n\v\f\r" // whitespace
"\0\xFE\xFF" // non-printing (used in various Unicode encodings)
) != string::npos)
returnfalse;
}
// If we get this far, then the file only contains whitespace
// (or its size is zero)
returntrue;
}
//----------------------------------------------------------------------------
int main( int argc, char** argv )
{
if ((argc < 2)
or (string( "?\0/?\0--help", 11 ).find( argv[ 1 ] ) != string::npos))
{
cout <<
"usage:\n " << argv[ 0 ] << " HELPOPT | FILELIST\n\n"" HELPOPT is one of\n"" ? /? --help\n\n"" FILELIST is a list of filenames separated by whitespace.\n\n""This program tells you whether or not a given text file is 'empty'.\n""An empty text file is one that contains no characters other than\n""ASCII whitespace for UTF-8, UTF-16, and UTF-32 encoded files.\n\n";
return 1;
}
for (int n = 1; n < argc; n++)
cout << (is_textfile_empty( argv[ n ] ) ? "empty: " : "full: ")
<< argv[ n ]
<< endl;
return 0;
}
I haven't tested this thoroughly... also, it only checks for ASCII whitespace characters 0, 9..13, and 32. There are a few other Unicode characters you may wish to test for...