2012-10-28 88 views
0

我正在嘗試使用fstream讀取文件。然後,當我到達終點我追加的文件,並寫入一些工作人員 文件在C++中使用fstream讀取和追加文件

abc 

我寫的示例代碼

#include<iostream> 
#include<fstream> 
#include<queue> 

using namespace std; 
int main(int argc, char **argv){ 
    fstream *binf; 
    binf=new fstream("t.txt", ios::out|ios::in|ios::app); 
    cout<<"EOF"<<EOF<<endl; 
    while(true){ 
     cout<<"before peek"<<endl; 
     cout<<"binf->tellg:"<<binf->tellg()<<endl; 
     cout<<"binf->tellp:"<<binf->tellp()<<endl; 
     cout<<"binf->peek()::int=("<<(int)binf->peek()<<")::char=("<<(char)binf->peek()<<")"<<endl; 
     cout<<"after peek"<<endl; 
     cout<<"binf->tellg:"<<binf->tellg()<<endl; 
     cout<<"binf->tellp:"<<binf->tellp()<<endl; 
     char c; 
     if(binf->peek()==EOF){ 
      cout<<"file is not good"<<endl; 
      break; 
     } 
     binf->get(c); 
    } 
    cout<<"binf->tellg:"<<binf->tellg()<<endl; 
    cout<<"binf->tellp:"<<binf->tellp()<<endl; 
    binf->seekg(3); 
    binf->seekp(3); 
    cout<<"binf->tellg:"<<binf->tellg()<<endl; 
    cout<<"binf->tellp:"<<binf->tellp()<<endl; 
    binf->put('H'); 
    cout<<"binf->tellg:"<<binf->tellg()<<endl; 
    cout<<"binf->tellp:"<<binf->tellp()<<endl; 
    binf->seekg(4); 
    char c; 
    binf->get(c); 
    cout<<"c:"<<c<<endl; 
    binf->clear(); 
    binf->close(); 
    delete binf; 
    return 0; 
} 

這是輸出我從這段代碼運行

EOF-1 
before peek 
binf->tellg:0 
binf->tellp:0 
binf->peek()::int=(97)::char=(a) 
after peek 
binf->tellg:0 
binf->tellp:0 
before peek 
binf->tellg:1 
binf->tellp:1 
binf->peek()::int=(98)::char=(b) 
after peek 
binf->tellg:1 
binf->tellp:1 
before peek 
binf->tellg:2 
binf->tellp:2 
binf->peek()::int=(99)::char=(c) 
after peek 
binf->tellg:2 
binf->tellp:2 
before peek 
binf->tellg:3 
binf->tellp:3 
binf->peek()::int=(10)::char=(
) 
after peek 
binf->tellg:3 
binf->tellp:3 
before peek 
binf->tellg:4 
binf->tellp:4 
binf->peek()::int=(-1)::char=(ÿ) 
after peek 
binf->tellg:-1 
binf->tellp:-1 
file is not good 
binf->tellg:-1 
binf->tellp:-1 
binf->tellg:-1 
binf->tellp:-1 
binf->tellg:-1 
binf->tellp:-1 
c: 
得到

我所要做的就是修復文件並在末尾寫入 但是,無論何時我在文件末尾看到EOF文件不再適合使用 即使偷看()

回答

2

當你點擊文件的最後,你把你的fstream錯誤狀態。當它處於錯誤狀態時,在清除錯誤狀態之前,什麼都不會起作用。所以你需要這個

if(binf->peek()==EOF){ 
     cout<<"file is not good"<<endl; 
     binf->clear(); // clear the error state 
     break; 
    } 

你不需要清除fstream之前關閉它,那什麼都不做。

順便說一句好的調試技術,但是如果你學會使用適當的調試器,你會發現這更容易。

+0

謝謝,你的回答非常明確。我認爲清楚會清除緩衝區內存。 – user1061392

+0

沒有'flush()',但是當你關閉流時也會自動發生。 – john

+0

是否有可能在文件乞討或文件中間找回並放入字符 – user1061392

相關問題