Namespaces
Variants

std::basic_filebuf<CharT,Traits>:: 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 ) ;

如果可能,将文件指针重新定位到由 sp 指示的位置。如果关联文件未打开( is_open ( ) == false ),则立即失败。

重新定位执行如下操作:

1) 若文件以写入模式打开,使用 overflow() 写入放置区域及当前植入区域设置所要求的任何反移序列。
2) 重新定位文件指针,如同调用 std::fsetpos()
3) 若文件以读取模式打开,必要时更新获取区域。

如果 sp 不是通过在同一文件上调用 seekoff() seekpos() 获得的,则行为未定义。

目录

参数

sp - 通过先前在同一文件上调用 seekoff() seekpos() 获取的文件位置
which - 定义要影响的输入和/或输出序列。可以是以下一个或多个常量的组合:
常量 说明
in 影响输入序列
out 影响输出序列

返回值

sp 表示成功,或 pos_type ( off_type ( - 1 ) ) 表示失败。

注释

seekpos() std::basic_streambuf::pubseekpos() 调用,而后者又由单参数版本的 std::basic_istream::seekg() std::basic_ostream::seekp() 调用。

许多实现不会在 seekpos() 中更新获取区域,而是委托给下一次 underflow() 调用,该调用由随后的 sgetc() 触发。

示例

在某些实现中,获取区域会被 seekpos() 清空,因此需要第二次 underflow() 才能观察到效果。

#include <fstream>
#include <iostream>
struct mybuf : std::filebuf
{
    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::filebuf::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";
// uncomment if get area is emptied by seekpos()
//        std::filebuf::underflow();
//        std::cout << "after forced underflow(), size of the get area is "
//                  << egptr() - eback() << " with "
//                  << egptr() - gptr() << " read positions available.\n";
        return rc;
    }
};
int main()
{
    mybuf buf;
    buf.open("test.txt", std::ios_base::in);
    std::istream stream(&buf);
    stream.get(); // read one char to force underflow()
    stream.seekg(2);
}

可能的输出:

Before seekpos(2), size of the get area is 110 with 109 read positions available.
seekpos() returns 2.
After the call, size of the get area is 110 with 108 read positions available.

缺陷报告

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

缺陷报告 适用标准 发布时行为 正确行为
LWG 55 C++98 seekpos 在失败时返回未定义的
无效流位置
pos_type ( off_type ( - 1 ) )
在失败时返回该值
LWG 171 C++98 重新定位操作序列不明确 已明确说明

参见

td> 使用相对寻址重新定位文件位置
(虚函数保护成员函数)
调用 seekpos ( )
(std::basic_streambuf<CharT,Traits> 的公开成员函数)
[virtual]
将文件位置指示器移动到文件中的特定位置
(函数)