Namespaces
Variants

std::basic_stringbuf<CharT,Traits,Allocator>:: seekoff

From cppreference.net
protected :

virtual pos_type seekoff ( off_type off,
std:: ios_base :: seekdir dir,

std:: ios_base :: openmode which = std:: ios_base :: in | std:: ios_base :: out ) ;

如果可能,将 std::basic_streambuf::gptr 和/或 std::basic_streambuf::pptr 重定位至缓冲区获取区和/或放置区的起始位置、末尾位置或当前位置偏移 off 个字符处。

如果 gptr 和/或 pptr 被重新定位,其操作按以下方式执行:

1) 确定类型为 off_type 的新指针偏移量 newoff
a) dir == std:: ios_base :: beg ,则 newoff 为零
b) dir == std:: ios_base :: cur ,则 newoff 为指针的当前位置( gptr ( ) - eback ( ) pptr ( ) - pbase ( )
c) dir == std:: ios_base :: end ,则 newoff 表示缓冲区已初始化部分的整体长度(若采用 超额分配 机制,则为高水位标记指针与起始指针的差值)
2) 若待重定位的指针为空指针且 newoff 将非零,则此函数执行失败。
3) newoff + off < 0 (重定位操作将使指针移动到缓冲区起始位置之前),或若 newoff + off 将指向缓冲区末端之后(若使用 过量分配 则指向缓冲区最后一个已初始化字符之后),则函数执行失败。
4) 否则,指针将按照 gptr ( ) = eback ( ) + newoff + off pptr ( ) = pbase ( ) + newoff + off 的方式被赋值。

目录

参数

off - 设置下一个指针的相对位置
dir - 定义应用相对偏移量的基准位置。可以是以下常量之一:
常量 说明
beg 流的起始位置
end 流的结束位置
cur 流位置指示器的当前位置
which - 定义影响输入序列、输出序列或两者。可以是以下常量之一或其组合:
常量 说明
in 影响输入序列
out 影响输出序列

返回值

pos_type ( newoff ) 成功时返回, pos_type ( off_type ( - 1 ) ) 在失败或当 pos_type 无法表示结果流位置时返回。

示例

#include <iostream>
#include <sstream>
int main()
{
    std::stringstream ss("123"); // 输入/输出
    std::cout << "写入位置 = " << ss.tellp()
              << " 读取位置 = " << ss.tellg() << '\n';
    // 绝对定位两个指针
    ss.rdbuf()->pubseekoff(1, std::ios_base::beg); // 将两个指针都向前移动1位
    std::cout << "写入位置 = " << ss.tellp()
              << " 读取位置 = " << ss.tellg() << '\n';
    // 尝试从当前位置将两个指针都向前移动1位
    if (-1 == ss.rdbuf()->pubseekoff(1, std::ios_base::cur))
        std::cout << "从当前位置移动两个指针失败\n";
    std::cout << "写入位置 = " << ss.tellp()
              << " 读取位置 = " << ss.tellg() << '\n';
    // 将写入指针向前移动1位,但不移动读取指针
    // 也可以调用为 ss.seekp(1, std::ios_base::cur);
    ss.rdbuf()->pubseekoff(1, std::ios_base::cur, std::ios_base::out);
    std::cout << "写入位置 = " << ss.tellp()
              << " 读取位置 = " << ss.tellg() << '\n';
    ss << 'a'; // 在写入位置写入
    std::cout << "在写入位置写入 'a' 后,缓冲区内容为 " << ss.str() << '\n';
    char ch;
    ss >> ch;
    std::cout << "在读取位置读取到字符 '" << ch << "'\n";
}

输出:

写入位置 = 0 读取位置 = 0
写入位置 = 1 读取位置 = 1
从当前位置移动两个指针失败
写入位置 = 1 读取位置 = 1
写入位置 = 2 读取位置 = 1
在写入位置写入 'a' 后,缓冲区内容为 12a
在读取位置读取到字符 '2'

缺陷报告

下列行为变更缺陷报告被追溯应用于先前发布的 C++ 标准。

缺陷报告 适用版本 发布时行为 正确行为
LWG 55 C++98 seekoff 在失败时返回未定义的
无效流位置
失败时返回
pos_type ( off_type ( - 1 ) )
LWG 375 C++98 std::ios_base 的静态常量成员被
错误指定为 std::basic_ios 的成员
已修正
LWG 432 C++98 即使 newoff + off 可能指向
最后一个初始化字符之后的位置, seekoff 仍可能成功
在此情况下
seekoff 会失败
LWG 453 C++98 重定位空的 gptr ( ) 和/或空的 pptr ( )
且新偏移量为零时总是失败
在此情况下可以成功
LWG 563 C++98 由于在解决 LWG 问题 432
程序无法精确控制结束指针,导致无法使用该指针计算 newoff
改用高水位标记指针
进行计算

参见

调用 seekoff ( )
( std::basic_streambuf<CharT,Traits> 的公开成员函数)
[virtual]
使用绝对寻址重定位输入序列、输出序列或两者的下一个指针
(虚受保护成员函数)
[virtual]
使用相对寻址重定位文件位置
( std::basic_filebuf<CharT,Traits> 的虚受保护成员函数)
[virtual]
使用相对寻址重定位输入序列、输出序列或两者的下一个指针
( std::strstreambuf 的虚受保护成员函数)