Search code examples
c++fstream

File not reading in correctly


I have a program that reads in a file. All my classes compile fine, but there seems to be an error when I read in the file. Eclipse shows an empty string is being read in (""), which is not what I want.

I have the code for my main below with a while loop. I placed the loop just to see how it would run when debugging, and it runs an infinite loop since it is always reading in "", and never reaches end of file. I have put the file in the working directory and every other folder just to be sure, but it is always doing this even though the file is full of strings and integers. Is there anything I am doing wrong here?

#include "Translator.h"
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>

using namespace std;

int main(int argc, char* argv[])
{
    ifstream readFile;
    readFile.open("sample.html");

    while (!readFile.eof()) // for debugging purposes only
    {
    string x;

    readFile >> x; // x is "" everytime through the loop
    readFile >> x; // x is also ""
    }
    Translator t(readFile);

    readFile.close();
    return 0;
}

Solution

  • My guess is that your file did not actually open, and the eof bit was therefore not set. You never test whether the file was opened successfully. It could be that your working directory is not what you think it is, or the file is locked by another process (perhaps open in a text editor).

    Officially, you can test readFile.fail() after you try opening.

    I've found that checking readFile.good() is fine too - in fact you can use that as your loop condition.

    I prefer the positive message of 'good' in my code, rather than the potentially upsetting 'fail'.

    You should also test your stream as WhozCraig suggested in comments, when you are reading data. You cannot assume that the operation was successful. If it fails for reasons other than EOF, you need to know.

    For these reasons, don't use readFile.eof() as your loop condition.