std::basic_istream<CharT,Traits>::seekg
来自 cppreference.cn
< cpp | io | basic istream
basic_istream& seekg( pos_type pos ); |
(1) | |
basic_istream& seekg( off_type off, std::ios_base::seekdir dir ); |
(2) | |
设置当前关联的 streambuf
对象的输入位置指示器。
在执行任何操作之前,seekg 清除 eofbit 。 |
(自 C++11 起) |
seekg
的行为类似于 UnformattedInputFunction,但 gcount() 不受影响。在构造并检查 sentry 对象后,
1) 如果 fail() != true,则将输入位置指示器设置为绝对值(相对于文件开头)pos。具体来说,执行 rdbuf()->pubseekpos(pos, std::ios_base::in) (pubseekpos 反过来调用特定缓冲区的 seekpos,例如 basic_filebuf::seekpos、basic_stringbuf::seekpos 或 strstreambuf::seekpos)。如果失败,则调用 setstate(std::ios_base::failbit)。
2) 如果 fail() != true,则将输入位置指示器设置为位置 off,相对于由 dir 定义的位置。具体来说,执行 rdbuf()->pubseekoff(off, dir, std::ios_base::in)。如果失败,则调用 setstate(std::ios_base::failbit)。
目录 |
[编辑] 参数
pos | - | 要将输入位置指示器设置到的绝对位置 | ||||||||
off | - | 要将输入位置指示器设置到的相对位置(正或负) | ||||||||
dir | - | 定义应用相对偏移量的基准位置。它可以是以下常量之一
|
[编辑] 返回值
*this
[编辑] 异常
如果内部操作抛出异常,则会捕获该异常并设置 badbit。如果为 badbit
设置了 exceptions(),则会重新抛出该异常。
[编辑] 注意
seekg(n) 不一定等同于 seekg(n, ios::beg)。std::basic_ifstream,例如,要求绝对位置 n 来自 tellg()。
[编辑] 示例
运行此代码
#include <iostream> #include <sstream> #include <string> int main() { std::string str = "Hello, world"; std::istringstream in(str); std::string word1, word2; in >> word1; in.seekg(0); // rewind in >> word2; std::cout << "word1 = " << word1 << '\n' << "word2 = " << word2 << '\n'; }
输出
word1 = Hello, word2 = Hello,
[编辑] 缺陷报告
以下行为更改缺陷报告被追溯应用于先前发布的 C++ 标准。
DR | 应用于 | 已发布行为 | 正确行为 |
---|---|---|---|
LWG 129 | C++98 | 没有办法指示失败 | 失败时设置 failbit |
LWG 136 | C++98 | seekg 可能会设置输出流 |
仅设置输入流 |
LWG 537 | C++98 | off 的类型为 off_type& |
更正为 off_type |
[编辑] 参见
返回输入位置指示器 (公共成员函数) | |
返回输出位置指示器 ( std::basic_ostream<CharT,Traits> 的公共成员函数) | |
设置输出位置指示器 ( std::basic_ostream<CharT,Traits> 的公共成员函数) | |
调用 seekpos() ( std::basic_streambuf<CharT,Traits> 的公共成员函数) | |
[虚拟] |
使用绝对寻址重新定位文件位置 ( std::basic_filebuf<CharT,Traits> 的虚拟保护成员函数) |
[虚拟] |
使用绝对寻址重新定位输入序列、输出序列或两者的下一个指针 ( std::basic_stringbuf<CharT,Traits,Allocator> 的虚拟保护成员函数) |
[虚拟] |
使用绝对寻址重新定位输入序列、输出序列或两者的下一个指针 ( std::strstreambuf 的虚拟保护成员函数) |
调用 seekoff() ( std::basic_streambuf<CharT,Traits> 的公共成员函数) | |
[虚拟] |
使用相对寻址重新定位文件位置 ( std::basic_filebuf<CharT,Traits> 的虚拟保护成员函数) |
[虚拟] |
使用相对寻址重新定位输入序列、输出序列或两者的下一个指针 ( std::basic_stringbuf<CharT,Traits,Allocator> 的虚拟保护成员函数) |
[虚拟] |
使用相对寻址重新定位输入序列、输出序列或两者的下一个指针 ( std::strstreambuf 的虚拟保护成员函数) |