簡體   English   中英

C ++ fstream:到達eof時引發異常

[英]C++ fstream: throwing exception when reaching eof

我想從兩個文件中讀取,直到到達其中一個的結尾。 如果出現問題,則fstream應該引發異常。

問題是,當設置eof位時,還會設置壞或失敗位。

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

怎么做對?

代碼中的基本問題是FAQ 你永遠不應該使用eof()作為讀取環路的測試條件,因為在C / C ++( 不像一些其他語言) eof()沒有被設置為true,直到您已經閱讀過去的文件的末尾,因此的身體循環將被輸入一次

習慣上正確的過程是使讀取操作本身處於循環狀態,以便退出在正確的位置進行:

  while ( input1.get(in1) && input2.get(in2) ) { /* etc */ }
  // here, after the loop, you can test eof(), fail(), etc 
  // if you're really interested in why the loop ended.

該循環將自然而然地用完較小的輸入文件,這正是您想要的。

只需刪除.eof() if(fstream)檢查所有位(eof壞和失敗)。

因此,將while重寫為:

 while(input1 && input2)

然后,也許驗證eof()對於流中的最后一個返回true。

希望這可以幫助。

根本不要引發異常,並使用input1.readistream::get進入while條件

while (input1.get(in1) && input2.get(in2)) {
...
}

如果在循環體中讀取了字符,則輸出中將有一個附加字符,沒有相應的輸入字符。 也許這就是為什么您首先使用std::ios::exeptions的原因。

暫無
暫無

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

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