std::basic_filebuf<CharT,Traits>:: seekoff
|
protected
:
virtual
pos_type seekoff
(
off_type off,
|
||
如果可能,将文件指针重新定位到距离文件开头、末尾或当前位置(取决于 dir 的值)恰好 off 个字符的位置。
如果关联文件未打开( 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() { // 准备一个包含4个UTF-8字符("zß水𝄋")的10字节文件 std::ofstream("text.txt") << "\x7a\xc3\x9f\xe6\xb0\xb4\xf0\x9d\x84\x8b"; // 使用非转换编码打开 std::ifstream f1("text.txt"); std::cout << "f1的locale的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的locale的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的locale的encoding()返回 1 pubseekoff(3, beg)返回 3 pubseekoff(0, end)返回 10 f2的locale的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>
的公开成员函数)
|
|
|
[virtual]
|
使用绝对寻址重定位文件位置
(虚函数保护成员函数) |
|
将文件位置指示器移动到文件中的特定位置
(函数) |