fstream的使用问题

来源:互联网 发布:农村淘宝会怎样发展 编辑:程序博客网 时间:2024/05/16 23:01

//使用fstream对象时,先读再写就会出问题,需要流指针重新定位才能写。先写再读没有问题,调用读操作流指针会自动右移一位再读

#include <iostream>
#include <fstream>
using namespace std;
int main()
{
fstream stream("hello.txt");
if(!stream)
{
cerr<<"file open failed"<<endl;
exit(-1);
}
char ch;
stream>>ch;
cout<<ch<<endl;
cout<<stream.tellg()<<endl;
cout<<stream.tellp()<<endl;
//stream.clear();
stream.seekp(2);
char c='2';
stream<<c;
cout<<stream.tellg()<<endl;
cout<<stream.tellp()<<endl;
stream>>ch;
cout<<ch<<endl;
cout<<stream.tellg()<<endl;
cout<<stream.tellp()<<endl;
stream.close();
return 0;
}

原创粉丝点击