std::basic_filebuf<CharT,Traits>::seekpos
来自 cppreference.cn
< cpp | io | basic filebuf
protected: virtual pos_type seekpos( pos_type sp, |
||
如果可能,将文件指针重新定位到 sp 指示的位置。如果关联文件未打开 (is_open() == false),则立即失败。
重新定位执行如下:
1) 如果文件已打开用于写入,则使用 overflow() 写入 put 区域和当前区域设置所需的任何 unshift 序列。
2) 重新定位文件指针,如同调用 std::fsetpos()。
3) 如果文件已打开用于读取,则在必要时更新 get 区域。
如果 sp 不是通过对同一文件调用 seekoff() 或 seekpos()
获得的,则行为未定义。
目录 |
[编辑] 参数
sp | - | 通过先前对同一文件调用 seekoff() 或 seekpos() 获得的文件位置 | ||||||
which | - | - 定义影响输入及/或输出序列的哪个。它可以是下列常量之一或组合
|
[编辑] 返回值
成功时返回 sp,失败时返回 pos_type(off_type(-1))。
[编辑] 注意
seekpos()
由 std::basic_streambuf::pubseekpos() 调用,后者由 std::basic_istream::seekg() 和 std::basic_ostream::seekp() 的单参数版本调用。
许多实现不会在 seekpos()
中更新 get 区域,而是委托给由下一个 sgetc() 调用的 underflow()。
[编辑] 示例
在某些实现中,get 区域由 seekpos()
清空,第二次 underflow()
对于观察效果是必要的。
运行此代码
#include <fstream> #include <iostream> struct mybuf : std::filebuf { pos_type seekpos(pos_type sp, std::ios_base::openmode which) { std::cout << "Before seekpos(" << sp << "), size of the get area is " << egptr() - eback() << " with " << egptr() - gptr() << " read positions available.\n"; pos_type rc = std::filebuf::seekpos(sp, which); std::cout << "seekpos() returns " << rc << ".\nAfter the call, " << "size of the get area is " << egptr() - eback() << " with " << egptr() - gptr() << " read positions available.\n"; // uncomment if get area is emptied by seekpos() // std::filebuf::underflow(); // std::cout << "after forced underflow(), size of the get area is " // << egptr() - eback() << " with " // << egptr() - gptr() << " read positions available.\n"; return rc; } }; int main() { mybuf buf; buf.open("test.txt", std::ios_base::in); std::istream stream(&buf); stream.get(); // read one char to force underflow() stream.seekg(2); }
可能的输出
Before seekpos(2), size of the get area is 110 with 109 read positions available. seekpos() returns 2. After the call, size of the get area is 110 with 108 read positions available.
[编辑] 缺陷报告
下列更改行为的缺陷报告追溯地应用于以前出版的 C++ 标准。
缺陷报告 | 应用于 | 发布时的行为 | 正确的行为 |
---|---|---|---|
LWG 55 | C++98 | seekpos 返回一个未定义值的非法流位置 |
pos_type(off_type(-1)) 在失败时返回 |
LWG 171 | C++98 | 重新定位操作的顺序不明确 | 已明确 |
[编辑] 另请参阅
调用 seekpos() ( std::basic_streambuf<CharT,Traits> 的公共成员函数) | |
[虚函数] |
使用相对地址重新定位文件位置 (虚保护成员函数) |
将文件位置指示器移动到文件中特定位置 (函数) |