最終更新日時:
が更新

履歴 編集

function
<fstream>

std::basic_filebuf::underflow

protected:
  virtual int_type underflow();  // (1) C++03
  int_type underflow() override; // (1) C++17

概要

入力部分列に文字がない場合に、ファイルから文字を読み込む。

このメンバ関数はprotectedであり、sgetc()などのpublicメンバ関数を通して間接的に呼び出される。

効果

basic_streambuf::underflow()の規定に従う。ただしbasic_filebufでは、入力シーケンスからの文字の読み取りが、ファイルから内部バッファ(下記のextern_buf)へ読み込み、それを以下のように変換したかのように行われる。

char         extern_buf[XSIZE];
const char*  extern_end;
charT        intern_buf[ISIZE];
charT*       intern_end;
codecvt_base::result r =
  a_codecvt.in(state, extern_buf, extern_buf+XSIZE, extern_end,
               intern_buf, intern_buf+ISIZE, intern_end);

ここでa_codecvtは、このストリームバッファに設定されているロケールのcodecvtファセットである。

この変換は、intern_bufintern_endの間の各文字に対応する位置(fpos_t)をクラスが復元できるような方法で行われる。rの値がa_codecvt.in()intern_bufの領域を使い切ったことを示す場合は、より大きなintern_bufで再試行する。

戻り値

basic_streambuf::underflow()と同じ。読み取りに成功した場合は次に読み取られる文字を、失敗した場合はTraits::eof()を返す。

#include <iostream>
#include <fstream>

// basic_filebufを継承して、protectedなunderflowの呼び出しを観測する
struct my_filebuf : std::filebuf {
protected:
  int_type underflow() override
  {
    std::cout << "underflow" << std::endl;
    return std::filebuf::underflow();
  }
};

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

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

  // get領域が空なので、underflow()が呼ばれる
  std::cout << static_cast<char>(buf.sgetc()) << std::endl;

  // 既に読み込み済みなので、underflow()は呼ばれない
  std::cout << static_cast<char>(buf.sgetc()) << std::endl;
}

出力

underflow
A
A

バージョン

言語

  • C++98

関連項目