std::basic_filebuf<CharT,Traits>::seekoff
| |
||
在可能时重寻位文件指针到距文件起始、结尾或当前位置恰好 off 个字符的位置(取决于 dir 的值)。
关联文件未打开(is_open() == false)时立即失败。
如果多字节字符编码依赖状态(codecvt::encoding() 返回 -1)或者是变长的(codecvt::encoding() 返回 0),而偏移 off 非 0,那么立即失败:此函数无法确定对应 off 个字符的字节数。
如果 dir 不是 std::basic_ios::cur 或偏移 off 非 0,并且此 filebuf 对象上最近做的操作是输出(即放置缓冲区非空,或最近调用的函数是 overflow()),那么就会调用 std::codecvt::unshift 以确定需要的反迁移序列,并通过调用 overflow() 将该序列写入文件。
然后转换实参 dir 到 int 类型值 whence 如下:
dir 的值
|
whence 的值
|
std::basic_ios::beg
|
SEEK_SET |
std::basic_ios::end
|
SEEK_END |
std::basic_ios::cur
|
SEEK_CUR |
然后,如果字符编码是定宽的codecvt::encoding() 返回某个正值 width),那么如同用 std::fseek(file, width*off, whence) 移动文件指针。
否则,如同用 std::fseek(file, 0, whence) 移动文件指针。
基类函数签名要求的 openmode 实参通常会被忽略,因为 std::basic_filebuf 只维护一个文件位置。
参数
| off | - | 要设置位置指示器到的相对位置。 | ||||||||
| dir | - | 定义要应用相对偏移到的基位置。它可以是下列常量之一:
| ||||||||
| which | - | 定义会影响到的输入和/或输出序列。它可以是下列常量之一或它们的组合:
|
返回值
新构造的 pos_type 类型对象,存储结果文件位置,或在失败时返回 pos_type(off_type(-1))。
注解
seekoff() 会被 std::basic_streambuf::pubseekoff 调用,它又会被 std::basic_istream::seekg、std::basic_ostream::seekp、std::basic_istream::tellg 和 std::basic_ostream::tellp 调用。
示例
#include <fstream>
#include <iostream>
#include <locale>
template<typename CharT>
int get_encoding(const std::basic_istream<CharT>& stream)
{
using Facet = std::codecvt<CharT, char, std::mbstate_t>;
return std::use_facet<Facet>(stream.getloc()).encoding();
}
int main()
{
// 准备 10 字节文件,保有 4 个 UTF-8 中的字符("zß水𝄋")
std::ofstream("text.txt") << "\x7a\xc3\x9f\xe6\xb0\xb4\xf0\x9d\x84\x8b";
// 用非转换编码打开
std::ifstream f1("text.txt");
std::cout << "f1 的本地环境的 encoding() 返回 "
<< get_encoding(f1) << '\n'
<< "pubseekoff(3, beg) 返回 "
<< f1.rdbuf()->pubseekoff(3, std::ios_base::beg) << '\n'
<< "pubseekoff(0, end) 返回 "
<< f1.rdbuf()->pubseekoff(0, std::ios_base::end) << '\n';
// 用 UTF-8 打开
std::wifstream f2("text.txt");
f2.imbue(std::locale("en_US.UTF-8"));
std::cout << "f2 的本地环境的 encoding() 返回 "
<< get_encoding(f2) << '\n'
<< "pubseekoff(3, beg) 返回 "
<< f2.rdbuf()->pubseekoff(3, std::ios_base::beg) << '\n'
<< "pubseekoff(0, end) 返回 "
<< f2.rdbuf()->pubseekoff(0, std::ios_base::end) << '\n';
}
输出:
f1 的本地环境的 encoding() 返回 1
pubseekoff(3, beg) 返回 3
pubseekoff(0, end) 返回 10
f2 的本地环境的 encoding() 返回 0
pubseekoff(3, beg) 返回 -1
pubseekoff(0, end) 返回 10
缺陷报告
下列更改行为的缺陷报告追溯地应用于以前出版的 C++ 标准。
| 缺陷报告 | 应用于 | 出版时的行为 | 正确行为 |
|---|---|---|---|
| LWG 55 | C++98 | seekoff 在失败时返回了未定义的无效流位置
|
失败时返回 pos_type(off_type(-1))
|
参阅
调用 seekoff() ( std::basic_streambuf<CharT,Traits> 的公开成员函数)
| |
[虚] |
用绝对寻址重寻位文件位置 (虚受保护成员函数) |
| 移动文件位置指示器到文件中的指定位置 (函数) |