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

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

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

std::streampos pos = 0;

while(true){

pos = stream.tellg()

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

stream.seekg(pos)

}

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

在有时候,我们需要从文档流中的特定位置读取数据,那么可以用tellg得到这个特定的位置,用seekg将文件流位置设为pos。

即:

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

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

但能够使用tellg和seekg精确定位的前提是,文档是以二进制形式打开的,即std::ios::binary。因为系统每次对文档中的符号的解读不一样,所以会导致seekg(pos)时,不能定位到我们想要的位置。

猜你喜欢

转载自www.cnblogs.com/mengmengmiaomiao/p/11666667.html