C + + input and output redirection

Source: Internet
Author: User

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;}

  

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.