Namespaces
Variants

std::basic_filebuf<CharT,Traits>:: seekpos

From cppreference.net
protected :

virtual pos_type seekpos ( pos_type sp,

std:: ios_base :: openmode which = std:: ios_base :: in | std:: ios_base :: out ) ;

可能であれば、ファイルポインタを sp で示される位置に再配置します。関連付けられたファイルが開かれていない場合( is_open ( ) == false )、直ちに失敗します。

Repositionは以下のように動作します:

1) ファイルが書き込み用に開かれている場合、現在組み込まれているロケールで要求されるプット領域と任意のアンシフトシーケンスを overflow() を使用して書き込みます。
2) ファイルポインタを再配置します。これは std::fsetpos() を呼び出した場合と同様です。
3) ファイルが読み取り用に開かれている場合、必要に応じてget領域を更新します。

sp が同じファイルに対する seekoff() または seekpos() の呼び出しによって取得されなかった場合、動作は未定義です。

目次

パラメータ

sp - 同じファイルに対して以前に呼び出された seekoff() または seekpos() によって取得されたファイル位置
which - 入力シーケンスおよび/または出力シーケンスのどれに影響を与えるかを定義する。以下の定数の1つまたは組み合わせを指定可能:
定数 説明
in 入力シーケンスに影響
out 出力シーケンスに影響

戻り値

sp 成功時、または pos_type ( off_type ( - 1 ) ) 失敗時。

注記

seekpos() std::basic_streambuf::pubseekpos() によって呼び出され、これは単一引数バージョンの std::basic_istream::seekg() および std::basic_ostream::seekp() によって呼び出されます。

多くの実装では、get領域を更新せず、 seekpos() の処理を underflow() に委譲し、これは次に呼び出される sgetc() によって実行されます。

一部の実装では、get領域は seekpos() によって空になり、効果を観察するには2回目の underflow() が必要です。

#include <fstream>
#include <iostream>
struct mybuf : std::filebuf
{
    pos_type seekpos(pos_type sp, std::ios_base::openmode which)
    {
        std::cout << "Before seekpos(" << sp << "), size of the get area is "
                  << egptr() - eback() << " with "
                  << egptr() - gptr() << " read positions available.\n";
        pos_type rc = std::filebuf::seekpos(sp, which);
        std::cout << "seekpos() returns " << rc << ".\nAfter the call, "
                  << "size of the get area is "
                  << egptr() - eback() << " with "
                  << egptr() - gptr() << " read positions available.\n";
// uncomment if get area is emptied by seekpos()
//        std::filebuf::underflow();
//        std::cout << "after forced underflow(), size of the get area is "
//                  << egptr() - eback() << " with "
//                  << egptr() - gptr() << " read positions available.\n";
        return rc;
    }
};
int main()
{
    mybuf buf;
    buf.open("test.txt", std::ios_base::in);
    std::istream stream(&buf);
    stream.get(); // read one char to force underflow()
    stream.seekg(2);
}

出力例:

Before seekpos(2), size of the get area is 110 with 109 read positions available.
seekpos() returns 2.
After the call, size of the get area is 110 with 108 read positions available.

欠陥報告

以下の動作変更の欠陥報告書は、以前に公開されたC++規格に対して遡及的に適用されました。

DR 適用対象 公開時の動作 正しい動作
LWG 55 C++98 seekpos は失敗時に未定義の
無効なストリーム位置を返した
pos_type ( off_type ( - 1 ) )
が失敗時に返される
LWG 171 C++98 再配置操作のシーケンスが明確ではなかった 明確化された

関連項目

seekposを呼び出す seekpos ( )
( std::basic_streambuf<CharT,Traits> の公開メンバ関数)
[virtual]
相対アドレス指定を使用してファイル位置を再配置する
(仮想保護メンバ関数)
ファイル位置指示子をファイル内の特定の位置に移動する
(関数)