流和文件指针移动

fstream and file pointer moving

本文关键字:移动 指针 文件      更新时间:2023-10-16

>我一直在尝试在重置文件指针位置之前保存文件指针位置,然后将其重新设置,但事情似乎没有像我想要的那样工作。

我想出了:

fstream f;
// open...
long long p = f.seekg(); // Save previous location
f.seekg(std::ios::beg);  // Set ptr to the file beginning
// Work with the file...
f.seekg(p);              // return ptr to the previous location (p)

如果我尝试在以下命令之后打印 fileptr 位置,则值为 -1。是因为我在处理文件时达到了 EOF 吗?如果我无法使用 seekg 将其设置回之前的位置,我应该考虑哪些其他选择?

谢谢

long long p = f.seekg();

甚至无法编译,您可能是指tellg.

f.seekg(std::ios::beg);

这是错误的; seekg有两个重载,一个接受流中的位置,另一个接受从某个特定位置的偏移量(使用枚举指定)。std::ios::beg/cur/end仅适用于其他重载。所以,在这里你想要

f.seekg(0, std::ios::beg);

而且,最重要的是,如果您的流处于脏状态(eof,失败,错误),则搜索不会产生任何影响。您必须先清除状态位,使用 f.clear() .

顺便说一下,如果你想安全地存储文件指针位置,你应该使用类型 std::istream::streampos .所以,总结一下:

std::istream::streampos p = f.tellg(); // or, in C++11: auto p = f.tellg();
// f.clear() here if there's a possibility that the stream is in a bad state
f.seekg(0, std::ios::beg);
// ...
f.clear();
f.seekg(p);

tellg 返回文件位置指示符:

std::istream::pos_type p = f.tellg();
//                           ^^^^^

如果遇到 EOF 键,请先重置标志

f.clear();                 // clear fail and eof bits
f.seekg(p, std::ios::beg);