开发者

fstream end of file question

开发者 https://www.devze.com 2023-03-05 18:51 出处:网络
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

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


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消