2011-05-01 71 views
2

當我使用ifstream來讀取文件時,我將遍歷文件中的所有行並關閉它。然後我嘗試用同一個ifstream對象打開一個不同的文件,但仍然說文件結尾錯誤。我想知道爲什麼關閉文件不會自動爲我清除狀態。那麼我必須在close()之後再顯式調用clear()爲什麼不關閉文件自動清除錯誤狀態?

他們有什麼理由將它設計成這樣嗎?對我來說,如果你想重複使用fstream對象來處理不同的文件,那真的很痛苦。

#include <iostream> 
#include <fstream> 
#include <string> 
using namespace std; 

void main() 
{ 
    ifstream input; 
    input.open("c:\\input.txt"); 

    string line; 
    while (!input.eof()) 
    { 
     getline(input, line); 
     cout<<line<<endl; 
    } 

    // OK, 1 is return here which means End-Of-File 
    cout<<input.rdstate()<<endl; 

    // Why this doesn't clear any error/state of the current file, i.e., EOF here? 
    input.close(); 

    // Now I want to open a new file 
    input.open("c:\\output.txt"); 

    // But I still get EOF error 
    cout<<input.rdstate()<<endl; 

    while (!input.eof()) 
    { 
     getline(input, line); 
     cout<<line<<endl; 
    } 
} 
+0

你爲什麼要閱讀輸出^ _ ^? – alternative 2011-05-01 16:17:09

+0

@mathepic,您可以隨時閱讀輸出文件,但不能寫入輸入文件。無論如何,這個名字應該不重要:) – 2011-05-01 16:20:23

+0

我當然可以寫入一個「input.txt」,並從「output.txt」中讀取,但這看起來確實很奇怪,不是嗎? – alternative 2011-05-01 16:53:34

回答

3

致電close可能會失敗。當它失敗時,它將設置failbit。如果它重置流的狀態,您將無法檢查對close的呼叫是否成功。

+1

行..但是隻有在關閉失敗的情況下,他們才能設置狀態。 – 2011-05-01 16:33:19

+0

然後,他們將不得不測試所有失敗的條件,而在目前的實施中,只有一個成功的測試。 – Dikei 2011-05-01 17:08:24

+0

但有沒有人測試過關閉失敗?我知道我從來不會這樣做。如果它失敗了,你會怎麼做? – 2011-05-01 17:45:18

1

因爲標誌與流關聯,而不是文件。

5

就我個人而言,我認爲close()應該重置標誌,因爲過去我一直被這個標誌咬住。不過,一旦安裝我的愛好馬多,你讀的代碼是錯誤的:

while (!input.eof()) 
{ 
    getline(input, line); 
    cout<<line<<endl; 
} 

應該是:

while (getline(input, line)) 
{ 
    cout<<line<<endl; 
} 

要知道爲什麼,考慮會發生什麼,如果你嘗試讀取一個完全空白文件。 eof()調用將返回false(因爲雖然文件是空的,但您還沒有讀取任何內容,只有讀取設置了eof位),您將輸出一條不存在的行。

+0

這是一個很好的觀點,謝謝。 – 2011-05-01 16:33:42

0

這已在C++ 11(C++ 0x)中進行了更改,並非如此,close()會丟棄檢測到的任何錯誤,但下一次打開()將爲您調用clear()。

相關問題