简体   繁体   中英

C++ Continue Reading File After eof()?

I am building a program which reads text files, containing a list of numbers. These lists contain a series of sorted numbers, each which may contain a varying amount of values. For example, file 1 may have a list of 2 numbers and file 2 may have a list of 20.

The point of the program is to read each of these text files (which contain numbers in ascending order) line by line, then put them into a new text file in ascending order. However, if one list is really short, then I will get an eof() error, causing the file reader to go into the fail state, which won't allow it to read the remaining values in the longer text file.

Here is my code which iterates over the two text files:

int main() {
int numbers1 = 0, numbers2 = 0, fillCounter = 0, iteration = 0;
char grabNext = 'b';
ifstream file1, file2, fileFiller;
ofstream fout;
file1.open("numbers1.txt");
file2.open("numbers2.txt");
fout.open("output.txt");

//Check and see if the opening operation was successful
if (file1.fail() || file2.fail()) {
    cout << "The progran could not open the related necessary files. Check and see if they exist!"
         << endl;

    exit(1);
}

do {
//In theory, whenever the file1 gives an eof, I should be able to iterate over the remaining lines of file2
    if (file1.eof()) {
        do {
            fout << numbers2 << endl;
        } while(!file2.eof());

        break;
    }

//In theory, whenever the file2 gives an eof, I should be able to iterate over the remaining lines of file1
    if (file2.eof()) {
        do {
            fout << numbers1 << endl;
            break;
        } while(!file1.eof());

        break;
    }

    if (grabNext == 'b') {
        file1 >> numbers1;
        file2 >> numbers2;
    } else if (grabNext == 'l') {
        file1 >> numbers1;
    } else if (grabNext == 'u') {
        file2 >> numbers2;
    }

    cout << numbers1 << " " << numbers2 << endl;

    if (numbers1 < numbers2) {
        fout << numbers1 << endl;
        grabNext = 'l';
    } else if (numbers1 > numbers2) {
        fout << numbers2 << endl;
        grabNext = 'u';
    }

    iteration++;
} while(true);

}

Here is example text file 1:

-1
3
5
7
9

Here is example text file 2:

2
4
10
12
16

My question is, after I reach eof() from one file, that I could continue to read the other until that one reaches eof() ?

I have been looking everywhere with no luck.

Thank you for your time.

Note that you also have infinite loops:

do {
        fout << numbers1 << endl;
        break;
    } while(!file1.eof());

Nothing is changing inside the loop to cause file1 to approach eof().

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM