std::strstreambuf::seekpos
来自 cppreference.cn
< cpp | io | strstreambuf
protected: virtual pos_type seekpos( pos_type sp, |
(在 C++98 中已弃用) (在 C++26 中移除) |
|
如果可能,将 std::basic_streambuf::gptr 和/或 std::basic_streambuf::pptr 重新定位到由 sp 指示的位置。
如果 std::ios_base::in 在 which 中设置,则尝试重新定位 gptr()
(get 区域中的下一个指针)。如果 std::ios_base::out 在 which 中设置,则尝试重新定位 pptr()
(put 区域中的下一个指针)。如果 which 中未设置任何位,则操作失败。
每个下一个指针的重新定位方式如下
- 如果下一个指针为空,则操作失败。
- 否则,通过调用 sp.offset() 确定新的偏移量 newoff (类型为
off_type
)。如果 newoff 为负数、超出缓冲区边界或无效,则操作失败。 - 否则,将下一个指针赋值,如同通过 gptr() = eback() + newoff 或 pptr() = pbase() + newoff。
目录 |
[编辑] 参数
sp | - | 流位置,例如通过 seekoff() 或 seekpos() 获得的位置 | ||||||
which | - | 定义输入序列、输出序列或两者是否受影响。它可以是以下常量之一或组合
|
[编辑] 返回值
成功时,结果偏移量转换为 pos_type
,失败时为 pos_type(off_type(-1))。
[编辑] 注释
seekpos()
由 std::basic_streambuf::pubseekpos() 调用,而 std::basic_streambuf::pubseekpos() 又由 std::basic_istream::seekg() 和 std::basic_ostream::seekp() 的单参数版本调用。
[编辑] 示例
运行此代码
#include <cstring> #include <iostream> #include <strstream> struct mybuf : std::strstreambuf { mybuf(const char* str) : std::strstreambuf(str, std::strlen(str)) {} 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::strstreambuf::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"; return rc; } }; int main() { mybuf buf("12345"); std::iostream stream(&buf); stream.seekg(2); }
输出
Before seekpos(2), size of the get area is 5 with 5 read positions available. seekpos() returns 2. After the call, size of the get area is 5 with 3 read positions available.
[编辑] 缺陷报告
以下行为变更缺陷报告被追溯应用于先前发布的 C++ 标准。
DR | 应用于 | 已发布行为 | 正确行为 |
---|---|---|---|
LWG 55 | C++98 | seekpos 返回未定义的失败时的无效流位置 |
pos_type(off_type(-1)) 失败时返回 |
[编辑] 参见
[virtual] |
使用相对寻址重新定位输入序列、输出序列或两者的下一个指针 (virtual protected member function) |
[virtual] |
使用绝对寻址重新定位输入序列、输出序列或两者的下一个指针 ( std::basic_streambuf<CharT,Traits> 的虚保护成员函数) |
[virtual] |
使用绝对寻址重新定位输入序列、输出序列或两者的下一个指针 ( std::basic_stringbuf<CharT,Traits,Allocator> 的虚保护成员函数) |
[virtual] |
使用绝对寻址重新定位文件位置 ( std::basic_filebuf<CharT,Traits> 的虚保护成员函数) |