5

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.

zhang zhengchi
  • 55
  • 1
  • 1
  • 5
  • How are you using `peek()`? The EOF flag is only set after a read reached the end of the file, by the way. – Ry- Oct 07 '14 at 04:16
  • Whoops again a missed this duplicate, there's hardly any question these days which ain't has any duplicate in one way or the other – P0W Oct 07 '14 at 04:30

4 Answers4

14

Use peek like following

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

}
P0W
  • 46,614
  • 9
  • 72
  • 119
3

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

Galik
  • 47,303
  • 4
  • 80
  • 117
2

If "empty" means that the length of the file is zero (i.e. no characters at all) then just find the length of the file and see if it's zero:

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

if (length == 0)
{
    // do your error handling
}
Adam
  • 16,808
  • 7
  • 52
  • 98
0
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;
Vikramjeet
  • 215
  • 6
  • 16