ランダムアクセスにはseekg(),seekp()を使う。seekg()はファイルの取得ポインタを、seekp()は出力ポインタを操作する。指定するパラメータは移動させるバイト数と基準となる位置の二つ。
istream &seekg(off_type offset, seekdir origin); ostream &seekp(off_type offset, seekdir origin);
基準となる位置seekdirには次の値が指定できる。
ios::beg ファイルの先頭 ios::cur 現在位置 ios::end ファイルの末尾
次のプログラムではファイルの先頭から123バイトの位置へ移動し、そこの文字を表示している。
#include <iostream> #include <fstream> using namespace std; int main() { ifstream in("test.bin", ios::binary); in.seekg( 123, ios::beg ); // ファイルの先頭から123バイトの位置へ char ch; in.get(ch); cout << ch << endl; in.close(); return 0; }