簡體   English   中英

C ++在eof()之后繼續讀取文件嗎?

[英]C++ Continue Reading File After eof()?

我正在構建一個程序,該程序讀取文本文件,其中包含數字列表。 這些列表包含一系列排序的數字,每個數字可能包含數量不等的值。 例如,文件1可能具有2個數字的列表,而文件2可能具有20個數字的列表。

該程序的重​​點是逐行讀取每個文本文件(其中包含按升序排列的數字),然后將它們按升序放入新的文本文件中。 但是,如果一個列表確實很短,那么我將收到一個eof()錯誤,導致文件讀取器進入失敗狀態,這將不允許它讀取較長文本文件中的其余值。

這是我的代碼,它遍歷兩個文本文件:

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

}

這是文本文件示例1:

-1
3
5
7
9

這是示例文本文件2:

2
4
10
12
16

我的問題是,當我從一個文件到達eof()之后,我可以繼續讀取另一個文件,直到那個文件到達eof()嗎?

我一直到處都沒有運氣。

感謝您的時間。

請注意,您還具有無限循環:

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

循環內部沒有任何改變導致file1接近eof()。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM