Default buffering in C++

Jonathan Wakely jwakely.gcc@gmail.com
Tue Mar 18 17:58:00 GMT 2014


On 18 March 2014 15:09, Abhishek Sharma wrote:
> I am observing the following behavior with the C++ Std library method
> std::ostream::write().
>
> For buffering the data I am making use of the following C++ API
>
> std::ofstream::rdbuf()->
> pubsetbuf(char* s, streamsize n)
>
> This works fine ( verified using the strace utility ) as long as the
> size of data (datasize) we are writing on the file stream using
>
> std::ofstream::write (const char* s, datasize n)
>
> Is less than 1023 bytes ( below this value the writes are accumulated
> till the buffer is not full), but when the size of data to write
> exceeds 1023, the buffer is not taken into account and the data is
> flushed to the file.

Yes, this is a hardcoded behaviour, see basic_filebuf::xsputn() in
include/bits/fstream.tcc


      // Optimization in the always_noconv() case, to be generalized in the
      // future: when __n is sufficiently large we write directly instead of
      // using the buffer.
      const bool __testout = (_M_mode & ios_base::out
                  || _M_mode & ios_base::app);
      if (__check_facet(_M_codecvt).always_noconv()
        && __testout && !_M_reading)
    {
      // Measurement would reveal the best choice.
      const streamsize __chunk = 1ul << 10;
      streamsize __bufavail = this->epptr() - this->pptr();

      // Don't mistake 'uncommitted' mode buffered with unbuffered.
      if (!_M_writing && _M_buf_size > 1)
        __bufavail = _M_buf_size - 1;

      const streamsize __limit = std::min(__chunk, __bufavail);
      if (__n >= __limit)
        {
          const streamsize __buffill = this->pptr() - this->pbase();
          const char* __buf = reinterpret_cast<const char*>(this->pbase());
          __ret = _M_file.xsputn_2(__buf, __buffill,
                       reinterpret_cast<const char*>(__s),
                       __n);

I don't think there's anything you can do to force it to use the buffer.



More information about the Libstdc++ mailing list