std::basic_stringbuf<CharT,Traits,Allocator>::seekoff
< cpp | io | basic stringbuf
protected: virtual pos_type seekoff(off_type off, |
||
若可能,则重寻位 std::basic_streambuf::gptr 和/或 std::basic_streambuf::pptr 到对应距流的获取和/或放置区起始、结尾或当前位置准确 off
个字符的位置。
- 若
which
包含ios_base::in
而此缓冲为读取打开(即 ((which & ios_base::in) == ios_base::in ),则重寻位获取区内的读指针 std::basic_streambuf::gptr 如后述 - 若
which
包含ios_base::out
而此缓冲为写入打开(即 (which & ios_base::out) == ios_base::out ),则重寻位放置区内的写指针 std::basic_streambuf::pptr 如后述 - 若
which
包含ios_base::in
和ios_base::out
两者而缓冲为读和写打开( (which & (ios_base::in|ios_base::out)) ==(ios_base::in|ios_base::out) )而dir
为 ios_base::beg 或 ios_base::end 之一,则重寻位读和写指针如后述。 - 否则,此函数失败。
若重寻位( gptr
或 pptr
或两者),则按下列方式进行:
1) 若要重寻位的指针为空指针且新偏移
newoff
会为非零,则函数失败。2) 确定
off_type
类型的新指针偏移 newoff
a) 若 dir == ios_base::beg ,则
newoff
为零b) 若 dir == ios_base::cur ,则
newoff
为指针的当前位置( gptr()-eback() 或 pptr()-pbase() )c) 若 dir == ios_base::end ,则
newoff
为缓冲区的整个已初始化部分的长度(若使用过分配,则为高水位指针减起始指针)3) 若 newoff + off < 0 (重寻位会移动指针到缓冲区的起始指针之前)或若 newoff + off 会指向缓冲区结尾后(或若使用过分配,则为缓冲区中最后未初始化字符之后),则函数失败
4) 否则,如同以 gptr() = eback() + newoff + off 或 pptr() = pbase() + newoff + off 赋值指针。
参数
off | - | 要设置下一位置指针到的相对位置 | ||||||||||
dir | - | 定义应用偏移到的基位置。它能为下列常量之一:
| ||||||||||
which | - | 定义影响的是输入序列、输出序列还是两者。它能为下列常量之一或其组合:
|
返回值
成功时为 pos_type(newoff) ,失败时或若 pos_type 不能表示结果流位置则为 pos_type(off_type(-1)) 。
示例
运行此代码
#include <iostream> #include <sstream> int main() { std::stringstream ss("123"); // 入/出 std::cout << "put pos = " << ss.tellp() << " get pos = " << ss.tellg() << '\n'; // 两个指针绝对寻位 ss.rdbuf()->pubseekoff(1, std::ios_base::beg); // 都前移 1 std::cout << "put pos = " << ss.tellp() << " get pos = " << ss.tellg() << '\n'; // 试图从当前位置前移两个指针 1 if(-1 == ss.rdbuf()->pubseekoff(1, std::ios_base::cur)) std::cout << "moving both pointers from current position failed\n"; std::cout << "put pos = " << ss.tellp() << " get pos = " << ss.tellg() << '\n'; // 前移写指针 1 ,但不前移读指 // can also be called as ss.seekp(1, std::ios_base::cur); ss.rdbuf()->pubseekoff(1, std::ios_base::cur, std::ios_base::out); std::cout << "put pos = " << ss.tellp() << " get pos = " << ss.tellg() << '\n'; ss << 'a'; // 写入输出位置 std::cout << "Wrote 'a' at put position, the buffer is now " << ss.str() << '\n'; char ch; ss >> ch; std::cout << "reading at get position gives '" << ch << "'\n"; }
输出:
put pos = 0 get pos = 0 put pos = 1 get pos = 1 moving both pointers from current position failed put pos = 1 get pos = 1 put pos = 2 get pos = 1 Wrote 'a' at put position, the buffer is now 12a reading at get position gives '2'
参阅
[虚] |
用绝对寻址重定位输入序列、输出序列或两者中的下一位置指针 ( std::basic_streambuf<CharT,Traits> 的虚受保护成员函数) |
[虚] |
用相对寻址重定位输入序列、输出序列或两者中的下一位置指针 ( std::basic_streambuf<CharT,Traits> 的虚受保护成员函数) |
[虚] |
用相对寻址重寻位文件位置 ( std::basic_filebuf<CharT,Traits> 的虚受保护成员函数) |