freopen() function in C++

In this guide, you will learn what is freopen() function is in C++ programming and how to use it with an example.

1. freopen() Function Overview

The freopen() function is part of the <cstdio> library in C++. It is used to open a file and associate the file with a specified stream. Additionally, it can change the file associated with an existing stream. One common use case is to redirect the standard input or output to a file.

Signature:

FILE* freopen(const char* filename, const char* mode, FILE* stream);

Parameters:

- filename: The name of the file to be associated with the stream.

- mode: The mode in which the file is to be accessed, e.g., "r", "w", "a", etc.

- stream: The existing stream with which the file will be associated. This can be stdin, stdout, or stderr.

2. Source Code Example

#include <iostream>
#include <cstdio>

int main() {
    // Redirect standard output to a file named "output.txt"
    freopen("output.txt", "w", stdout);

    // Print to standard output (now, the content will be written to "output.txt")
    std::cout << "This message will be written to the file output.txt" << std::endl;

    // Resetting standard output back to console (for demonstration purposes only)
    freopen("CON", "w", stdout);
    std::cout << "This message will be displayed on the console." << std::endl;

    return 0;
}

Output:

This message will be displayed on the console.

3. Explanation

1. We first use freopen() to redirect the standard output (stdout) to a file named "output.txt".

2. Any content printed to standard output using std::cout will now be written to "output.txt".

3. For demonstration, we reset the standard output back to the console using freopen("CON", "w", stdout);. This is platform-specific and might not work on non-Windows systems.

4. After resetting, any content printed to standard output will be displayed on the console as usual.


Comments