public member function
<ios> <iostream>

std::basic_ios::rdbuf

get (1)
basic_streambuf<char_type,traits_type>* rdbuf() const;
set (2)
basic_streambuf<char_type,traits_type>* rdbuf (basic_streambuf<char_type,traits_type>* sb);
Get/set stream buffer
The first form (1) returns a pointer to the stream buffer object currently associated with the stream.

The second form (2) also sets the object pointed by sb as the stream buffer associated with the stream and clears the error state flags.

If sb is a null pointer, the function automatically sets the badbit error state flags (which may throw an exception if member exceptions has been passed badbit).

Some derived stream classes (such as string streams and file streams) maintain their own internal stream buffer, to which they are associated on construction. Calling this function to change the associated stream buffer shall have no effect on that internal stream buffer: the stream will have an associated stream buffer which is different from its internal stream buffer (although input/output operations on streams always use the associated stream buffer, as returned by this member function).

Parameters

sb
Pointer to a basic_streambuf object with the same template parameters as the basic_ios object.
char_type and traits_type are member types defined as aliases of the first and second class template parameters, respectively (see basic_ios types).

Return Value

A pointer to the stream buffer object associated with the stream before the call.

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// redirecting cout's output thrrough its stream buffer
#include <iostream>     // std::streambuf, std::cout
#include <fstream>      // std::ofstream

int main () {
  std::streambuf *psbuf, *backup;
  std::ofstream filestr;
  filestr.open ("test.txt");

  backup = std::cout.rdbuf();     // back up cout's streambuf

  psbuf = filestr.rdbuf();        // get file's streambuf
  std::cout.rdbuf(psbuf);         // assign streambuf to cout

  std::cout << "This is written to the file";

  std::cout.rdbuf(backup);        // restore cout's original streambuf

  filestr.close();

  return 0;
}

This example uses both function forms: first to get a pointer to a file's basic_streambuf object and then to assign it to cout.

Data races

Accesses (1) or modifies (2) the stream object.
Concurrent access to the same stream object may cause data races.

Exception safety

Basic guarantee: if an exception is thrown, the stream is in a valid state.
It throws an exception of member type failure if sb is a null pointer and member exceptions was set to throw for badbit.

See also