前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >ifstream seekg 问题

ifstream seekg 问题

作者头像
全栈程序员站长
发布2022-08-11 19:31:53
5030
发布2022-08-11 19:31:53
举报

大家好,又见面了,我是你们的朋友全栈君。

文件输入流(ifstream)读到文件尾之后,调用seekg 重定向 读pos

类似于以下代码片段:

代码语言:javascript
复制
//read whole file
while(ifs.readline(str,strLen)){
    std::cout << line++ << " : "<<str<<std::endl;
}



ifs.seekg(0,std::ios::beg);//rewind to beginning of the file //1
ifs.clear();//clear eof flag                                 //2

std::cout <<"+++++++++++++++++++++++++++++++"<<std::endl;
//read whole file again
line = 0;
while(ifs.readline(str,strLen)){//发生错误,不能继续读文件
    std::cout << line++ << " : "<<str<<std::endl;
}

发现重新读文件的时候 发生错误,不能继续读文件。

查看seekg的说明之后,发现

ifstream seekg 问题
ifstream seekg 问题

如果 ifstream 的 eofbit 没有被清除,seekg 会失败。

改成如下代码之后,程序正常了。

代码语言:javascript
复制
//read whole file
while(ifs.readline(str,strLen)){
    std::cout << line++ << " : "<<str<<std::endl;
}


ifs.clear();//clear eof flag first                                //2
ifs.seekg(0,std::ios::beg);//then rewind to beginning of the file //1


std::cout <<"+++++++++++++++++++++++++++++++"<<std::endl;
//read whole file again
line = 0;
while(ifs.readline(str,strLen)){//发生错误,不能继续读文件
    std::cout << line++ << " : "<<str<<std::endl;
}

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/130992.html原文链接:https://javaforall.cn

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022年4月2,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档