std::basic_istream<CharT,Traits>::seekg
来自cppreference.com
| |
(1) | |
| |
(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,则设置输入位置指示器为相对于 dir 所定义位置的 off。具体而言,执行 rdbuf()->pubseekoff(off, dir, std::ios_base::in)。失败的情况下会调用 setstate(std::ios_base::failbit)。参数
| pos | - | 设置输入位置指示器到的绝对位置。 | ||||||||
| off | - | 设置输入位置指示器到的相对位置(正或负)。 | ||||||||
| dir | - | 定义应用相对偏移量的基位置。它可以是下列常量之一:
|
返回值
*this
异常
在出现错误(错误状态标志不是 goodbit)并且 exceptions() 已设置为对该状态抛出时,会抛出 failure。
如果内部操作抛出了异常,那么捕获它并设置 badbit。如果 exceptions() 设置了 badbit,那么就会重抛该异常。
注解
seekg(n) 不必等价于 seekg(n, ios::beg)。例如,std::basic_ifstream 要求来自 tellg() 的绝对位置 n。
示例
运行此代码
#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); // 回溯
in >> word2;
std::cout << "word1 = " << word1 << '\n'
<< "word2 = " << word2 << '\n';
}
输出:
word1 = Hello,
word2 = Hello,
缺陷报告
下列更改行为的缺陷报告追溯地应用于以前出版的 C++ 标准。
| 缺陷报告 | 应用于 | 出版时的行为 | 正确行为 |
|---|---|---|---|
| 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 的虚受保护成员函数) |