seekg()与tellg()在文档中定位某行不正确的缘由

string in_path = "/home/XX/a.prototxt";ios

stream = ifstream(in_path, std::ios::binary);文档

std::streampos pos = 0;get

while(true){string

pos = stream.tellg()io

std::istream& ret = stream.getline(line, sizeof(line));stream

stream.seekg(pos)二进制

}数据

 

以上这段代码,可以重复读文档中的位置为pos的行,文件

在有时候,咱们须要从文档流中的特定位置读取数据,那么能够用tellg获得这个特定的位置,用seekg将文件流位置设为pos。while

即:

stream.tellg()可以给出当前读到了文档中哪个位置,

stream.seekg(pos)可以设置下次开始读的位置为pos。

但可以使用tellg和seekg精肯定位的前提是,文档是以二进制形式打开的,即std::ios::binary。由于系统每次对文档中的符号的解读不同,因此会致使seekg(pos)时,不能定位到咱们想要的位置。

相关文章
相关标签/搜索