
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
I/O Redirection in C++
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.
- istream : Stream, that can support input only
- ostream : Stream, that can support output only
- iostream : These can be used for input and output.
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:
- Get the stream buffer A, and store it
- Set stream buffer A to another stream buffer B
- Reset the stream buffer A to its previous position (Optional)
Example Code
#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(); }
Output
Again in Cout buffer for console
abcd.txt
This string will be stored into the File