Example of C++ I and O redirection method

  • 2020-06-07 05:00:21
  • OfStack

What is a redirection

Redirect is changing an application's original operation object to something else. For example, instead of receiving information from a keyboard, my program now receives information from a file called config.ini. I'm going to print it out to result.txt text and save it.

This article mainly introduces the C++ input and output redirection related content, sharing for your reference learning value, the following words do not say much, let's have a look at the detailed introduction

C++ mid-stream (stream) is 1 object, so any object that has the behavior of a stream is also a stream object.

There are three main types of flows:

istream: Mainly performs input operations from streams ostream: Mainly performs output operations from streams iostream: Mainly performs input/output operations from streams

Each stream object is associated with a stream, buffer. Program 1 typically reads from buffer, so if you want to redirect the stream, you simply point the buffer object to another stream.

All stream objects are associated with one class member data, streambuf, which is the buffer for stream (buffer). C++ reads input and output from buffer, not from the source stream.

We perform a redirect operation using ios::rdbuf() Methods. For this method, if no arguments are passed, the buffer pointer to the stream object is returned directly. If an buffer pointer to a flow object is passed, bind the current flow object to buffer of that flow object that is passed.

Example:


stream_object.rdbuf(); // Return stream object buffer
stream_object.rdbuf(streambuf * p); // Bound flow object buffer

Practical operation:


// cout  Redirect to a 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 the file and bind to ios::out object 
 string line;
 
 //  First get cout , cin the buffer Pointer to the 
 streambuf *stream_buffer_cout = cout.rdbuf();
 streambuf *stream_buffer_cin = cin.rdbuf();
 
 //  Retrievable buffer Pointer to the 
 streambuf *stream_buffer_file = file.rdbuf();
 
 // cout Redirect to a file 
 cout.rdbuf(stream_buffer_file);
 
 cout << "This line written to file" << endl;
 
 // cout Redirected to cout , output to the screen 
 cout.rdbuf(stream_buffer_cout);
 cout << "This line is written to screen" << endl;
 
 file.close(); //  Close the file 
 return 0;
}

conclusion


Related articles: