C++ IOS Library - rdbuf


Advertisements

Description

It is used to get/set stream buffer. 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 stringstream and fstream) 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).

Declaration

Following is the declaration for ios::rdbuf function.

get (1)	streambuf* rdbuf() const;
set (2)	streambuf* rdbuf (streambuf* sb);

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.

Parameters

sb − Pointer to a streambuf object.

Return Value

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

Exceptions

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.

Data races

Accesses (1) or modifies (2) the stream object.

Concurrent access to the same stream object may cause data races.

Example

In below example explains about ios::rdbuf function.

#include <iostream>     
#include <fstream>      

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

   backup = std::cout.rdbuf();     

   psbuf = filestr.rdbuf();        
   std::cout.rdbuf(psbuf);         

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

   std::cout.rdbuf(backup);        

   filestr.close();

   return 0;
}
ios.htm
Advertisements