Mr. Nicky Mr. Nicky - 1 month ago 10
C++ Question

End of file check doesn't work (C++)

We have a file with integers. There's an integer on each line. We have to go through the file and find the minimum and maximum integer. Everything's clear on what to do, but I have a problem with case when the file is empty.

Here's my code:

#include <iostream>
#include <fstream>
using namespace std;

void calculateMinMax(ifstream& inputStream, int& minNum, int& maxNum)
{
string currLine;
if(inputStream.ios::eof()) // code never enters this, even if file is empty !???
{
throw "EmptyFileException";
}

int currNum;

inputStream >> minNum;
maxNum = minNum;

while(getline (inputStream, currLine))
{
inputStream >> currNum;

if(currNum > maxNum)
{
maxNum = currNum;
}

if(currNum < minNum)
{
minNum = currNum;
}
}

inputStream.close();
}

int main()
{
int currNum, minNum, maxNum;
ifstream inputStream("numberFile.txt");

try
{
calculateMinMax(inputStream, minNum, maxNum);
cout << "Min: " << minNum << endl;
cout << "Max: " << maxNum << endl;
}
catch(...)
{
cout << "File is empty" << endl;
}

return 0;
}


The probelem is on the line where I'm checking whether the file is empty or not. I have no idea why that's happening, it just continues executing without exceptions even if it's empty. Any suggestions?

Answer
if(inputStream.ios::eof()) // code never enters this, even if file is empty !???
{
    throw "EmptyFileException";
}

Very simple reason for this. The file stream has no way of knowing that you have reached the end of the file until it finds the end of the file. The only way to find the end of the file is to read from the file until a read fails because the end has been reached.

If the file is empty, the first read will fail and the EOF bit will be set. You can check this with a peek as covered in Checking for an empty file in C++

Off topic: This is clunky: inputStream.ios::eof(). inputStream.eof() is sufficient and possibly safer on the off chance std::ifstream overrides eof() with something more substantial than a check of the EOF bit.

Comments