public member function
<istream> <iostream>

std::basic_istream::seekg

(1)
basic_istream& seekg (pos_type pos);
(2)
basic_istream& seekg (off_type off, ios_base::seekdir way);
設定輸入序列中的位置
設定從輸入流中提取的下一個字元的位置。

在內部,該函式首先構造一個 sentry 物件(將 noskipws 設定為 true)來訪問輸入序列。然後(如果 good),它在其關聯的 流緩衝區 物件(如果有)上呼叫 pubseekpos (1)pubseekoff (2)。最後,在返回之前銷燬 sentry 物件。

如果在呼叫之前設定了 eofbit 標誌,則函式失敗(設定 failbit 並返回)。
該函式會清除在呼叫之前設定的 eofbit 標誌。

呼叫此函式不會改變 gcount 返回的值。

引數

pos
在流內的新的絕對位置(相對於開頭)。
成員型別 pos_type字元特性 決定:通常,它是一個 fpos 型別(如 streampos),可以與整數型別相互轉換。
off
偏移量,相對於 way 引數。
成員型別 off_type 由 *字元特性* 確定:通常,它是已簽名整型 streamoff 的別名。
way
型別為 ios_base::seekdir 的物件。它可以接受以下任何常量值
偏移量相對於...
ios_base::beg流的開頭
ios_base::cur流中的當前位置
ios_base::end流的末尾

返回值

*thisbasic_istream 物件。

錯誤透過修改 內部狀態標誌 來指示
flagerror
eofbit-
failbit要麼是 sentry 的構造失敗,要麼是內部呼叫 pubseekpos (1)pubseekoff (2) 失敗(即,任一函式返回 -1)。
badbit流上發生了其他錯誤(例如,當函式捕獲由內部操作丟擲的異常時)。
當設定此標誌時,流的完整性可能已受到影響。
一次操作可能會設定多個標誌。

如果操作設定了透過成員 exceptions 註冊的 內部狀態標誌,則函式將丟擲型別為 failure 的異常。

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// read a file into memory
#include <iostream>     // std::cout
#include <fstream>      // std::ifstream

int main () {
  std::ifstream is ("test.txt", std::ifstream::binary);
  if (is) {
    // get length of file:
    is.seekg (0, is.end);
    int length = is.tellg();
    is.seekg (0, is.beg);

    // allocate memory:
    char * buffer = new char [length];

    // read data as a block:
    is.read (buffer,length);

    is.close();

    // print content:
    std::cout.write (buffer,length);

    delete[] buffer;
  }

  return 0;
}

在此示例中,seekg 用於將位置移到檔案末尾,然後移回開頭。

資料競爭

修改流物件。
併發訪問同一個流物件可能導致資料爭用。

異常安全

基本保證:如果丟擲異常,物件處於有效狀態。
如果結果的 錯誤狀態標誌 不是 goodbitexceptions 的該狀態設定為丟擲,則丟擲型別為 failure 的異常。
內部操作丟擲的任何異常都會被函式捕獲和處理,並設定 badbit。如果在最後一次呼叫 exceptions 時設定了 badbit,則函式將重新丟擲捕獲的異常。

另見