Chris Dargis
Chris Dargis

Reputation: 6043

fstream end of file question

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;
    }

Upvotes: 4

Views: 8776

Answers (2)

Robᵩ
Robᵩ

Reputation: 168646

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.

Upvotes: 3

user2100815
user2100815

Reputation:

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.

Upvotes: 2

Related Questions