命名空间
变体
操作

std::basic_filebuf<CharT,Traits>::seekpos

来自 cppreference.cn
< cpp‎ | io‎ | basic filebuf
 
 
 
 
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() 的单参数版本会调用 std::basic_streambuf::pubseekpos()

许多实现不在 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++ 标准。

DR 应用于 已发布行为 正确行为
LWG 55 C++98 seekpos 返回未定义的
失败时返回无效的流位置
pos_type(off_type(-1))
失败时返回
LWG 171 C++98 重新定位操作的顺序不明确 已明确

[编辑] 参见

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