當我使用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;
}
}
你爲什麼要閱讀輸出^ _ ^? – alternative 2011-05-01 16:17:09
@mathepic,您可以隨時閱讀輸出文件,但不能寫入輸入文件。無論如何,這個名字應該不重要:) – 2011-05-01 16:20:23
我當然可以寫入一個「input.txt」,並從「output.txt」中讀取,但這看起來確實很奇怪,不是嗎? – alternative 2011-05-01 16:53:34