4

I am reading in multiple files. There are roughly 300 of these files. For some reason, if I set the loop to run over 3 iterations, the while loop which is supposed to iterate through each line becomes infinite. My question is: Is there somthing I am forgetting to include in my while loop? For now I am simply trying to read one line at a time, eventually saving some data in the output file. Or is it possible that there is something contained in the data files that is not letting the program reach the end of the file?

ifstream inFile;
ofstream outFile;
char outputFilename[] = "output.txt";
int i;

outFile.open(outputFilename, ios::out);

for (i = 1; i < 4; i++) {
    stringstream inputFilename;
    inputFilename << "data/" << i << ".txt";
    inFile.open(inputFilename.str().c_str(), ios::in);
    if (!inFile) {
        cout << "Error opening input files" << endl;
        exit(-1);
    }

    char buffer[256];
    while (!inFile.eof()) {
        cout << "HEY";
        inFile.getline(buffer, 100);
    }
    inFile.close();
}
outFile.close();

Update: This works much better

char buffer[256];
    while (!inFile.eof()) {
      inFile >> buffer;
    }
Chris Dargis
  • 5,891
  • 4
  • 39
  • 63

2 Answers2

3

It makes no sense to check for end-of-file before you read. Try this loop contruct instead:

    char buffer[256];
    while (inFile.getline(buffer, 100)) {
      cout << "HEY";
    }

or, better yet,

    std::string buffer;
    while (std::getline(inFile, buffer)) {
      cout << "HEY";
    }

EDIT: Fix stoopid bug in string version.

Robᵩ
  • 163,533
  • 20
  • 239
  • 308
  • @VanDang - I have absolutely no idea how your program can enter an infinite loop, nor how this correction could fix it. I suppose there is more to your program than you showing us. – Robᵩ May 12 '11 at 21:51
  • @Rob: The only thing I left out was which head files were included. And, this code snippet was part of the main function. – Chris Dargis May 12 '11 at 21:54
  • It should be `std::getline(infile, buffer)`. – Puppy May 12 '11 at 22:19
  • When `istream::getline` encounters a line longer than its buffer, it sets the fail bit. Once in that state, `getline` never returns useful data, and never advances the input seek pointer. Thus, eof is never encountered, and `inFile.eof()` never returns true. – Robᵩ May 12 '11 at 22:21
2

Yet again!

Apart from anything else this:

while (!inFile.eof()) {
          cout << "HEY";
          inFile.getline(buffer, 100);

should be:

while ( inFile.getline(buffer, 100) ) {
          cout << "HEY";

as a moments thought or a consultation of your documents for eof() will tell you.

  • Thank you! It now works perfectly, would you care to explain this? – Chris Dargis May 12 '11 at 21:46
  • @Van It is only sensible to test eof() after a read. It tests if the read failed because of an end-of-file condition. Testing it before a read is therefore nuts. –  May 12 '11 at 21:59