• Class / Function / Type

      std::
    • Header file

      <>
    • Other / All

    最終更新日時(UTC):
    が更新

    履歴 編集

    function
    <istream>

    std::basic_istream::seekg

    basic_istream<CharT, Traits>& seekg(pos_type pos);
    basic_istream<CharT, Traits>& seekg(off_type off, seekdir dir);
    

    概要

    (非書式化入力関数)ストリームバッファに対し、読み取り位置の移動を指示する。

    非書式化入力関数であるが、後続のgcount()呼び出しに影響を及ぼさない点が通常と異なる。

    seekgは、seek getの略称。「読み取り用の位置の移動」を意味する。

    効果

    1. pos_typeを引数に取るもののみ)初めにeofbitを消去する。
    2. sentryオブジェクトを構築する。sentryオブジェクトが失敗を示した場合、何もしない。
    3. 与えられた実引数により、以下のいずれかを実行する。
      • rdbuf()->pubseekpos(pos, ios_base::in)
      • rdbuf()->pubseekoff(off, dir, ios_base::in)
    4. 失敗した場合、setstate(failbit)を呼び出す。

    戻り値

    *this

    以下は、off_typeseekdirを使用する例。 pos_typeのみを引数に取るオーバーロードの例は、tellgを参照。

    #include <iostream>
    #include <sstream>
    
    int main() {
      std::istringstream is("ABC");
      char x;
    
      is >> x;
      std::cout << x << std::endl;
    
      is.seekg(0, std::ios_base::beg);
      is >> x;
      std::cout << x << std::endl;
    }
    

    出力

    A
    A
    

    実装例

    basic_istream<CharT, Traits>& seekg(pos_type pos) {
      iostate state = goodbit;
      try {
        this->clear(this->rdstate() & ~eofbit);
        sentry s(*this, true);
        if (s) {
          if (this->rdbuf()->pubseekpos(pos, ios_base::in) == -1) {
            state |= failbit;
          }
        }
      } catch (...) {
        例外を投げずにbadbitを設定する;
        if ((this->exceptions() & badbit) != 0) {
          throw;
        }
      }
      this->setstate(state);
      return *this;
    }
    
    basic_istream<CharT, Traits>& seekg(off_type off, seekdir dir) {
      iostate state = goodbit;
      try {
        sentry s(*this, true);
        if (s) {
          if (this->rdbuf()->pubseekoff(off, dir, ios_base::in) == -1) {
            state |= failbit;
          }
        }
      } catch (...) {
        例外を投げずにbadbitを設定する;
        if ((this->exceptions() & badbit) != 0) {
          throw;
        }
      }
      this->setstate(state);
      return *this;
    }
    

    バージョン

    言語

    • C++98

    参照