A C + + stream is an object, so any object that has a stream of this behavior is also a stream object.
The flow is divided into three main types:
- IStream: The main step is to perform input operations from the stream
- Ostream: Output operation is primarily performed from the stream
- Iostream: Mainly performing input and output operations from a stream
Each stream object is associated with a stream buffer, and the program generally reads the data from buffer, so if you want to redirect the stream, simply point the buffer object to another stream.
All stream objects are associated with a class member data Streambuf, which is the buffer of the stream. C + + reads the input and output from buffer instead of the source data stream.
We perform a redirect operation using the Ios::rdbuf () method. For this method, if the parameter is not passed, the buffer pointer of the stream object is returned directly. If a buffer pointer is passed for a Stream object, the current stream object is bound to the buffer of the stream object passed.
Example:
Stream_object.rdbuf (); Returns the Stream object Bufferstream_object.rdbuf (STREAMBUF * p); Bound Stream Object Buffer
Actual operation:
cout Redirect to file # include <fstream> #include <iostream> #include <string> using namespace std; int main () { fstream file;//define FStream object file.open ("D:\cout.txt", ios::out);//Open file and bind to Ios::out object string line; First get the buffer pointer of cout, cin streambuf *stream_buffer_cout = Cout.rdbuf (); Streambuf *stream_buffer_cin = Cin.rdbuf (); Gets the buffer pointer of the file streambuf *stream_buffer_file = File.rdbuf (); cout Redirect to File cout.rdbuf (stream_buffer_file); cout << "This line written to file" << Endl; cout Redirect to cout, i.e. output to screen cout.rdbuf (stream_buffer_cout); cout << "This line is written-screen" << Endl; File.close (); Close file return 0;}