C++ Reference ยท Strings and I/O
C++ stream buffers and rdbuf()
Reference for C++ stream buffers: what std::streambuf does, how rdbuf() redirects cout, copies whole streams, and how a custom buffer plugs into any stream.
Every iostream is split in two. The stream object (std::cout, std::ifstream, std::stringstream) handles formatting and parsing: it turns an int into digits or digits into an int. A separate stream buffer, derived from std::streambuf, moves raw characters to and from the real destination: the console, a file or a string. The stream only talks to its buffer.
The member function rdbuf() gives you access to that buffer. Called without arguments it returns a pointer to the current buffer. Called with a pointer it installs a different buffer and returns the old one. That one function is enough to redirect std::cout into a string, to copy a whole stream in a single statement, or to attach your own buffer class that counts, filters or duplicates characters.
std::streambuf* old = std::cout.rdbuf(other.rdbuf()); // redirect std::cout.rdbuf(old); // restore
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.
Syntax
std::streambuf* basic_ios::rdbuf() const; std::streambuf* basic_ios::rdbuf(std::streambuf* sb); std::ostream& ostream::operator<<(std::streambuf* sb);
| Name | Description |
|---|---|
sb |
The buffer to install. The stream does not take ownership; you must keep sb alive for as long as the stream uses it. A null pointer is allowed and puts the stream into a bad state. |
Returns: the getter returns the buffer in use. The setter returns the buffer that was installed before and clears the stream's error state (clear() is called).
Two members of basic_stringstream and basic_fstream are also named rdbuf(): they return a pointer to the internal basic_stringbuf or basic_filebuf, which is what you pass to another stream's rdbuf(sb).
Undefined behavior / pitfalls: destroying the buffer while a stream still points at it, and leaving std::cout redirected into an object that goes out of scope, are the classic mistakes. Writing to such a stream is undefined behavior.
Usage notes
- Restore what you replace. Keep the pointer returned by
rdbuf(sb)and put it back before the replacement buffer is destroyed. A small RAII guard class makes this exception safe. os << is.rdbuf()copies all remaining characters from the input buffer to the output stream in one step, without formatting. If it inserts no characters at all, the output stream setsfailbit(for example when the source is empty).- Custom buffers override a few virtual functions. For output,
overflow(int_type)receives one character (or a signal to flush when given EOF) andxsputncan handle blocks. For input, overrideunderflow()(peek the next character) anduflow(). Without a buffer area set up bysetp(), each character goes throughoverflow, which is simple but slower than a buffered implementation. - Synchronization with C stdio. By default
std::coutis synchronized with C'sstdout, which makes it behave like an unbuffered stream.std::ios::sync_with_stdio(false)removes that cost, but it must be called before any I/O and you should not mixprintfandcoutafterwards. - Buffering is not formatting. The buffer knows nothing about numbers, widths or precision. Those live in the stream object (
std::ios_base) and stay with the stream when you swap the buffer. std::flush,std::endlandunitbufend up calling the buffer'spubsync(), which writes pending characters to the real destination.- Reading the whole file into a string is possible with
std::ostringstream ss; ss << file.rdbuf();.