返回文件起始位置

zedzhao 2008-12-25 08:20:34

#include <iostream>
using namespace std;

#include <fstream>
using namespace std;


ifstream& open_file(ifstream& ,const string);


int main()
{
ifstream ifile;
open_file(ifile,"t.txt");

char ch;

ifstream::pos_type mark = ifile.tellg();
while(ifile.get(ch))
cout << ch << " ";
ifile.seekg(mark); //mark换成 ios_base::beg也不行??

cout << endl;
while(ifile.get(ch))
cout << ch << " ";


ifile.close();
}

ifstream& open_file(ifstream &in,const string fileName)
{
in.close();
in.clear();

in.open(fileName.c_str(),ios::in);

if(!in)
cerr <<"can't open file" <<in<<endl;
return in;
}
应该seekg()函数就可以 ,这里有什么问题啊? seekg(0,ios_base::beg)也不行的
...全文
118 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
zedzhao 2008-12-25
  • 打赏
  • 举报
回复
3Q
lann64 2008-12-25
  • 打赏
  • 举报
回复
#include <iostream>
using namespace std;

#include <fstream>
using namespace std;


ifstream& open_file(ifstream& ,const string);


int main()
{
ifstream ifile;
open_file(ifile,"t.txt");

char ch;

ifstream::pos_type mark = ifile.tellg();
while (ifile.get(ch)) //这里把EOF置位了
cout << ch << " ";
ifile.clear(); //不清除EOF置位,后面的文件操作直接被跳过去,不会实际执行。
ifile.seekg(mark); //mark换成 ios_base::beg也不行??

cout << endl;
while (ifile.get(ch))
cout << ch << " ";


ifile.close();
}

ifstream& open_file(ifstream &in,const string fileName)
{
in.close();
in.clear();

in.open(fileName.c_str(),ios::in);

if (!in)
cerr <<"can't open file" <<in<<endl;
return in;
}
lann64 2008-12-25
  • 打赏
  • 举报
回复
没什么问题,加上,ifile.clear()

65,211

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧