[英]reading and appending a file using fstream in 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時,即使使用peek(),文件也不再好用
當您點擊文件末尾時,您將fstream
置於錯誤狀態 。 當它處於錯誤狀態時,在清除錯誤狀態之前沒有任何工作。 所以你需要這個
if(binf->peek()==EOF){
cout<<"file is not good"<<endl;
binf->clear(); // clear the error state
break;
}
你不需要在關閉它之前清除fstream
,它什么都不做。
BTW良好的調試技術,但如果你學會使用適當的調試器,你會發現這更容易。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.