我想从两个文件中读取,直到到达其中一个文件的末尾。如果出现问题,fstream 应该抛出异常。
问题是,当设置了 eof 位时,也会设置 bad 或 fail 位。
ifstream input1;
input1.exceptions(ios_base::failbit | ios_base::badbit);
input1.open("input1", ios_base::binary | ios_base::in);
ifstream input2;
input2.exceptions(ios_base::failbit | ios_base::badbit);
input2.open("input2", ios_base::binary | ios_base::in);
ofstream output;
output.exceptions(ios_base::failbit | ios_base:: badbit);
output.open("output", ios_base::binary | ios_base::out | ios_base::trunc);
char in1, in2, out;
while(!input1.eof() && !input2.eof()) {
input1.read((char*) &in1, 1);
input2.read((char*) &in2, 1);
out = in1^in2;
output.write((const char*) &out, 1);
}
input1.close();
input2.close();
output.close();
这将导致
$ ./test
terminate called after throwing an instance of 'std::ios_base::failure'
what(): basic_ios::clear
怎么做才对?