In C, we can use the freopen() function for redirection purposes. Using this function, we can redirect existing FILE pointer to another stream. The syntax of the freopen is like below:
FILE *freopen(const char* filename, const char* mode, FILE *stream)
In C++ also, we can do the redirection. In C++, the streams are used. Here we can use our own stream, and also redirect system streams. In C++, there are three types of streams.
These classes, and file stream classes are derived from the ios and stream-buf class. So the filestream and IO stream objects behave similarly. C++ allows to set the stream buffer to any stream. So we can simply change the stream buffer associated with the stream for redirecting. For an example, if there are two streams A and B, and we want to redirect Stream A to Stream B, we need to follow these steps:
#include <fstream> #include <iostream> #include <string> using namespace std; int main() { fstream fs; fs.open("abcd.txt", ios::out); string lin; // Make a backup of stream buffer streambuf* sb_cout = cout.rdbuf(); streambuf* sb_cin = cin.rdbuf(); // Get the file stream buffer streambuf* sb_file = fs.rdbuf(); // Now cout will point to file cout.rdbuf(sb_file); cout << "This string will be stored into the File" << endl; //get the previous buffer from backup cout.rdbuf(sb_cout); cout << "Again in Cout buffer for console" << endl; fs.close(); }
Again in Cout buffer for console
This string will be stored into the File