繁体   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