Namespaces
Variants

std::strstreambuf:: seekpos

From cppreference.net
protected :

virtual pos_type seekpos ( pos_type sp,
std:: ios_base :: openmode which =

std:: ios_base :: in | std:: ios_base :: out ) ;
(C++98 中已弃用)
(C++26 中移除)

如果可能,将 std::basic_streambuf::gptr 和/或 std::basic_streambuf::pptr 重新定位到 sp 指示的位置。

如果 std::ios_base::in which 中被设置,则尝试重新定位 gptr() (获取区域中的下一个指针)。如果 std::ios_base::out which 中被设置,则尝试重新定位 pptr() (放置区域中的下一个指针)。如果 which 中未设置任何位,则操作失败。

每个 next 指针按以下方式重新定位:

  • 如果下一个指针为空,则操作失败。
  • 否则,新的偏移量 newoff (类型为 off_type )通过调用 sp. offset ( ) 确定。如果 newoff 为负数、超出缓冲区边界或无效,则操作失败。
  • 否则,下一个指针的赋值方式相当于 gptr ( ) = eback ( ) + newoff pptr ( ) = pbase ( ) + newoff

目录

参数

sp - 流位置,例如通过 seekoff() seekpos() 获取的位置
which - 定义受影响的是输入序列、输出序列还是两者。可以是以下常量之一或其组合:
常量 说明
in 影响输入序列
out 影响输出序列

返回值

成功时返回转换为 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 ) )
在失败时返回此值

参见

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