最終更新日時:
が更新

履歴 編集

function
<fstream>

std::basic_filebuf::seekoff

protected:
  virtual pos_type
    seekoff(off_type off,
            ios_base::seekdir way,
            ios_base::openmode which = ios_base::in | ios_base::out);  // (1) C++03
  pos_type
    seekoff(off_type off,
            ios_base::seekdir way,
            ios_base::openmode which = ios_base::in | ios_base::out) override; // (1) C++17

概要

相対位置指定でファイル位置を移動する。

このメンバ関数はprotectedであり、std::basic_streambufpublicメンバ関数pubseekoff()を通して間接的に呼び出される。

効果

現在のロケールのcodecvtファセットのencoding()の値をwidthとする。

  • is_open()== falseである場合、もしくはoff != 0 && width <= 0である場合、位置指定操作は失敗する
  • そうでない場合、way !=ios_base::curもしくはoff != 0であり、かつ直前の操作が出力であった場合は、出力シーケンスを更新し、シフト状態を戻すシーケンス(unshift sequence)を書き込む
  • 続いて新しい位置へ移動する。width > 0の場合はstd::fseek(file, width * off, whence)を、そうでない場合はstd::fseek(file, 0, whence)を呼び出す

whenceの値は、wayの値に応じて以下のように決まる。

wayの値 stdioでの対応する値
ios_base::beg SEEK_SET
ios_base::cur SEEK_CUR
ios_base::end SEEK_END

戻り値

可能であれば、移動結果のストリーム位置を保持するpos_typeオブジェクトを構築して返す。

位置指定操作が失敗した場合、または移動結果のストリーム位置をpos_typeオブジェクトで表現できない場合は、pos_type(off_type(-1))を返す。

備考

「直前の操作が出力であった」とは、直前の仮想関数の操作がoverflowであったか、もしくはput領域が空でないことを意味する。

「シフト状態を戻すシーケンスを書き込む」とは、widthが負である場合にcodecvtファセットのunshift()を呼び出し、その結果得られたシーケンスを出力することを意味する。

#include <iostream>
#include <fstream>

int main()
{
  {
    std::filebuf out;
    out.open("test.txt", std::ios_base::out);
    out.sputn("ABCDE", 5);
  }

  std::filebuf buf;
  buf.open("test.txt", std::ios_base::in);

  // 先頭から2文字目へ移動する
  buf.pubseekoff(2, std::ios_base::beg);
  std::cout << static_cast<char>(buf.sbumpc()) << std::endl;

  // 現在位置から1文字進める
  buf.pubseekoff(1, std::ios_base::cur);
  std::cout << static_cast<char>(buf.sbumpc()) << std::endl;
}

出力

C
E

バージョン

言語

  • C++98

関連項目

参照