流和文件指针移动
fstream and file pointer moving
>我一直在尝试在重置文件指针位置之前保存文件指针位置,然后将其重新设置,但事情似乎没有像我想要的那样工作。
我想出了:
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);
相关文章:
- 何时在引用或唯一指针上使用移动语义
- 如何从具有移动语义的类对象中生成共享指针
- MSVC将仅移动结构参数解释为指针
- c++在使用指针时移动语义
- 数组指针表示法C++(移动数组时)
- 如何检索指向在单独线程上运行的函数的移动指针?
- 如何在将原始指针移动到基类构造函数之前从unique_ptr中提取原始指针
- 移动指针是否经过结构成员 UB?并访问它?
- C++标准::移动指针
- SetFilePointer不会失败,但也不会移动指针
- 如果允许 JVM 在垃圾回收期间移动堆内存,那么垃圾回收如何不会导致 JNI 因移动指针而爆炸
- C++ 通过移动指针在数组中导航
- 移动指针的右值引用
- 移动指针类型的构造函数
- 如何在C++中移动指针
- 展开数组对象并移动指针
- "Cannot"移动指针
- 移动指针与动态内存c++
- 在链表中移动指针
- 在vector中的vector之间移动指针会导致vector迭代器不兼容