ifstream seekg 问题

ifstream seekg 问题文件输入流(ifstream)读到文件尾之后,调用seekg重定向读pos类似于以下代码片段://readwholefilewhile(ifs.readline(str,strLen)){std::cout<<line++<<":"<<str<<std::endl;}ifs.seekg(0,std:…

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

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

类似于以下代码片段:

//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 的 eofbit 没有被清除,seekg 会失败。

 

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

 

//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.net/130992.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号