Open In App

I/O Redirection in C++

Last Updated : 15 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In C++, input and output operations are done in the form of sequence of bytes called stream through the stream objects like cin and cout. These objects use different components such as buffers, streams, etc. to efficiently read and write data to standard input and output devices such as keyboard and monitor.

data-flow-in-cin-and-cout

Buffer is a temporary storage that is connected to the stream. It holds the input/output data and passes it to the stream specific number of characters are reached. This reduces the expensive calls to the operating system.

What is I/O Redirection?

I/O redirection is a way to change the normal data flow of the input and output stream objects and redirect it from its default stream to some new stream. For example, the cout object prints the data to the console by default, but we can redirect it to any other stream such as a text file. Same thing can be done to any of the opened stream.

I/O Redirection in C++

In C++, redirection of streams is possible with the help of ios::rdbuf(). It is the member function in all of the stream objects such as cin, cout, cerr, etc.

Syntax

C
stream_object.rdbuf(sb);

This function returns the current buffer associated with the stream_object. It takes an optional parameter which is used to change the associated buffer to the buffer pointed by sb.

In C++, stream buffers are represented by streambuf class. It contains the mechanism to read/write data using system calls. It also stores the information of the source/destination of the input and output. So, changing the associated buffer allows us to change source/destination for that particular stream object.

Example: Redirecting cout to a File

By default, cout output the data to the console screen. In the below program, we will redirect its output to a file.

C++
#include <bits/stdc++.h>
using namespace std;

int main() {
    
    // Create an output stream to a file
    ofstream file;
    file.open("writeFile.txt");
    
    // Store default cout's buffer
    streambuf* cout_buf = cout.rdbuf();

    // Get the streambuf of the file
    streambuf* file_buf = file.rdbuf();

    // Redirect cout to the file by setting
    // cout's buffer to the file's buffer
    cout.rdbuf(file_buf);

    cout << "This line will be written to " <<
    "'writeFile.txt'";
    
    // Flush to ensure all the data is written
    cout.flush();
    
    // Redirect cout back to its default buffer
    // Good practice
    cout.rdbuf(cout_buf);
    
    cout << "This line will be writtein to console";
    
    // Close the file stream
    file.close();
    return 0;
}

Output
This line will be written to the console

Explanation: In the above example, we first created a file stream to writeFile.txt. Then we redirected cout to this file by replacing the cout's default buffer with the writeFile stream's buffer.

rdbuf
Write File

Internal Working of ios::rdbuf()

The rdbuf() function manipulates the internal buffer of the stream object (cout, cin, etc.). Below points shows, how ios::rdbuf() change the internal buffer of the stream:

  • A backup of the original stream buffer (e.g., cout_buffer) is created.
  • The stream buffer of the desired output (e.g., file) is assigned to the stream (e.g., cout).
  • After the redirection is done, the output is written to the file instead of the console.
  • After the task is completed, the stream buffer is reset back to the original buffer, and output will return to the console.

Let's take one more example, like cout can be redirected, we can also redirect cin to read from a file instead of the standard input (keyboard). For example, if we have a file that contains input data, then we can redirect cin to read from that file.

Example: Redirecting cin to a File

C++
#include <bits/stdc++.h>
using namespace std;

int main() {
    fstream file;
    
    // Open file for reading
    file.open("writeFile.txt", ios::in);
    string line;

    // Backup the original streambuf of cin
    streambuf* cin_buffer = cin.rdbuf();

    // Get the streambuf of the file
    streambuf* file_buffer = file.rdbuf();

    // Redirect cin to the file
    cin.rdbuf(file_buffer);

    // Now cin will read from 
    // "wFile.txt" instead of keyboard
    getline(cin, line);
    
    // Print the file string
    cout << line;

    // Set cin's buffer back 
    // to the original console buffer
    cin.rdbuf(cin_buffer);
    file.close();
    return 0;
}


Output

This line will be written to 'writeFile.txt'

Redirection with freopen()

It's a method to achieve I/O redirection in C++, but this method is inherited from the C language.

Syntax:

C++
freopen (fileName, mode, stream);

where,

  • fileName: Representing the path to the file you want to redirect to or from.
  • mode: Specifying the file access mode like read mode (r).
  • stream: A pointer to an existing standard C++ file stream that you want to redirect.

Return Value: freopen() returns a pointer to the newly reopened file stream if successful otherwise return NULL.

Example:

C++
#include <bits/stdc++.h>
using namespace std;
int main() {
    
    // Redirect standard output (stdout) to 
    // "output_freopen.txt" in write mode ("w")
    if (freopen("output_freopen.txt", "w", stdout) == NULL) {
        cerr << "Error redirecting stdout!" << endl;
    }
    
    // Output write in the output_freopen.text file
    cout << "This output will be written to 'output_freopen.txt'" << endl;
    cout << "Another line to the file.";

    return 0;
}


Output

This output will be written to 'output_freopen.txt'
Another line to the file.

Explanation: In the example above, instead of displaying output on the console or screen using cout, we write output to the file "output_freopen.txt". When cout is used, it writes output to the "output_freopen.txt" file.

freopen
Text File

Need of I/O Redirection

There are following points to enhance the program if we change the standard I/O working:

  • Automation: Run programs repeatedly with the same input data without manually typing it each time. This is essential for testing and batch processing.
  • Data Pipelines: Connect the output of one program as the input of another program, creating powerful processing workflows in scripting and command-line environments.
  • Testing and Debugging: Easily test your program with various input scenarios by simply changing the input file. Capture program output to files for detailed analysis and comparison with expected results.
  • Logging and Monitoring: Redirect program output, especially error streams, to log files. This creates a record of program activity, useful for debugging, auditing, and system monitoring.
  • Clean Console Output: Keep your console clear of program output when you want to examine the results later in a file, or when you are running programs in the background.

Differences between ios::rdbuf() and freopen()

We can achieve I/O redirection with both methods, but there are some key differences between them, which are mentioned below:

ios::rdbuf()freopen()
Used to get or set the stream buffer of an istream or ostream.Used to associate an existing file with a stream, typically to redirect the standard input/output.
Allows changing the underlying buffer of a stream to redirect input/output to a different buffer.Redirects a stream to a different file or device (e.g., stdin, stdout, or stderr).
Primarily used for low-level control over stream buffering and to change the stream’s internal buffer.Typically used to redirect standard streams (stdin, stdout, stderr) to files or other streams.
Only affects the internal buffer of the stream and does not change the file descriptor or the stream's properties.Changes the stream’s file descriptor and redirects input/output to the specified file.
Allows direct control of buffering mechanisms (e.g., switching to a different buffer).No direct control over buffering, it just redirects the input/output stream.

Next Article
Practice Tags :

Similar Reads