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 所指示的位置。
如果在 which 中设置了 std::ios_base::in,则尝试重新定位 gptr()
(获取区域中的下一个指针)。如果在 which 中设置了 std::ios_base::out,则尝试重新定位 pptr()
(放置区域中的下一个指针)。如果 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_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++ 标准。
缺陷报告 | 应用于 | 发布时的行为 | 正确的行为 |
---|---|---|---|
LWG 55 | C++98 | seekpos 返回一个未定义的的非法流位置 |
pos_type(off_type(-1)) 在失败时返回 |
[编辑] 另请参阅
[虚拟] |
使用相对寻址重新定位输入序列、输出序列或两者的下一个指针 (虚拟保护成员函数) |
[虚拟] |
使用绝对寻址重新定位输入序列、输出序列或两者的下一个指针 ( std::basic_streambuf<CharT,Traits> 的虚拟保护成员函数) |
[虚拟] |
使用绝对寻址重新定位输入序列、输出序列或两者的下一个指针 ( std::basic_stringbuf<CharT,Traits,Allocator> 的虚拟保护成员函数) |
[虚拟] |
使用绝对地址重新定位文件位置 ( std::basic_filebuf<CharT,Traits> 的虚拟保护成员函数) |