C ++では、システムはどのようにバッファーストリームを実装しますか?

StackOverflow https://stackoverflow.com/questions/1584380

  •  21-09-2019
  •  | 
  •  

質問

誰かがこの概念を説明するためにいくつかのサンプルコードを書くことができますか?バッファリングされたストリームが使用されるものは知っていますが、それを実装する方法も知りたいと思います。

前もって感謝します!

役に立ちましたか?

解決

プラットフォームの実装、C ++標準、または Angelika LangerとKlaus Kreftによる「標準C ++ ioStreams and Locales」.

かなりの学習曲線に備えてください。ストリームは古く、複雑な問題です。 (フランシス・グラスボー: 「I/Oライブラリがあらゆる言語の最も困難な側面の1つであることに疑問はほとんどありません。」)

他のヒント

「入力」ストリームの場合、概略的に:

class BufferedInputStream
{
public:
  BufferedInputStream(SomeExternalDevice d)
  : m_Device(d),
    m_Current(m_Buffer),
    m_End(m_Buffer)
  {}

  char get(){
    if (!IsDataAvailableInBuffer()){
      ReadAChunkFromDiskAndPutItInBuffer();
    }
    return PopByteFromBuffer();
  }

private:

  bool IsDataAvailableInBuffer()const{
    return m_Current != m_End;
  }

  void ReadAChunkFromDiskAndPutItInBuffer(){
    // Buffer must be empty
    assert(!IsDataAvailableInBuffer());

    // Read bytes from the device
    bytes_read = Read(m_Device, m_Buffer, BufferSize);

    // Reposition the "begin" and "end" pointers
    m_Current = m_Buffer;
    m_End = m_Buffer + bytes_read;
  }

  char PopByteFromBuffer(){
    assert(IsDataAvailableInBuffer());
    return *m_Current++;
  }

  // For example, an OS file handle
  SomeExternalDevice m_Device;

  // The buffer itself
  char m_Buffer[BufferSize];

  // Begin of buffer contents
  char* m_Current;

  // End of buffer contents
  char* m_End;
};

そうすれば、データはバッファーのサイズのチャンクのディスクから読み取られ、ほとんどの呼び出しは「get()」への呼び出しは、バッファからバイトを単純に返すことができるため、OSへの呼び出しで終わる必要はありません。

STLの実装をご覧くださいSSTREAMsstream.tcc (SGI STL実装へのリンク)。

本拠 stringstream クラスはです basic_stringstream, 、それを実装します basic_iostream インターフェース。

  // [27.7.4] Template class basic_stringstream
  /**
   *  @brief  Controlling input and output for std::string.
   *
   *  This class supports reading from and writing to objects of type
   *  std::basic_string, using the inherited functions from
   *  std::basic_iostream.  To control the associated sequence, an instance
   *  of std::basic_stringbuf is used, which this page refers to as @c sb.
  */

基本クラスがあります basic_stringbuf から派生します basic_streambuf. 。これにより、バッファが保持されます。

  // [27.7.1] template class basic_stringbuf
  /**
   *  @brief  The actual work of input and output (for std::string).
   *
   *  This class associates either or both of its input and output sequences
   *  with a sequence of characters, which can be initialized from, or made
   *  available as, a @c std::basic_string.  (Paraphrased from [27.7.1]/1.)
   *
   *  For this class, open modes (of type @c ios_base::openmode) have
   *  @c in set if the input sequence can be read, and @c out set if the
   *  output sequence can be written.
  */
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top