Freopen() function in C

Reopening an existing file stream (FILE*) with a different file or mode is possible in C due to the freopen() function. Linking those to new files enables you to redirect standard input, output, or error streams. The function is used to do operations like routing output to files and modifying the file that a stream writes to or reads from. The file name, mode, and stream are the same parameters as those of fopen(). The freopen() function closes the original file linked to the stream. The original stream remains unchanged if the function fails and returns NULL.

Syntax:

It has the following syntax:

Parameters:

  1. FILE *: It indicates that a pointer to a FILE object is what the function returns. This FILE reference represents the new opened file stream.
  2. const char *filename: It is a pointer to the name of the file that has to be opened in a string. Instead of opening a new file, freopen() modifies the mode of the currently open file stream if filename is NULL.
  3. const char *mode: This is a pointer to a string (such as "r" for reading and "w" for writing) that indicates the file access mode. It specifies how to open the file or make changes to the current file stream.
  4. FILE *stream: This is a pointer to the FILE stream that is currently open that you want to redirect or reopen. The stream might be a user-defined file stream or one of the standard streams (stdin, stdout, stderr).

The mode parameter's possible values are:

Text File Modes:

Several Text File Modes are as follows:

  1. "r": It allows for the reading of an already existing file. The function will not work if the file is not present. It is not possible to edit the file.
  2. "w": It creates a new writing file. The contents of the file are deleted if it already exists. If it's not there, a new file is made. Reading from the file is not possible in this mode.
    "a": It opens a current file so that data can be appended at the end. If the file doesn't already exist, it is created. Data is added at the end of the file in this manner, which allows writing without modifying the content that already exists.
  3. "r+": It allows the file to be opened for reading and writing. There must be a file. The file's content remains unchanged, allowing both reading and update of the file.
  4. "w+": It creates a new file for reading and writing. It is cleared if the file already exists. A new file is created if it doesn't already exist. The file is truncated if it already exists, although reading and writing are still permitted in this mode.
  5. "a+": It opens an already-existing file for appending and reading. It creates the file if it doesn't already exist. Data is added at the end of the file in this manner, which allows writing without modifying the content that already exists.

Binary File Modes:

Several binary File Modes are as follows:

  1. "rb": It allows you to read an already-existing binary file. The file needs to be there. When the data is read in binary format, no modifications are possible.
  2. "wb": It creates a new binary file suitable for writing. If the file already exists, its contents are erased. If not, a new file is created. This mode does not allow reading but does allow writing of binary data.
  3. "ab": It allows data to be appended at the end of an already-existing binary file. If the file doesn't already exist, it is created. This mode adds binary data without altering the content that already exists.
  4. "r+b" or "rb+": It allows you to read and write to an already-existing binary file. The file needs to be there. The content of the file can be updated in this manner without erasing it.
  5. "w+b" or "wb+": It creates a new binary file that can be written to and read from. If the file already exists, its contents are erased. If not, a new file is created. This mode allows writing and reading and truncates the file if it already exists.
  6. "a+b" or "ab+": It allows you to read and append to an already-existing binary file. The file is generated if it doesn't already exist. Binary formatted data is attached, and the file can be read from any location.

Return Value:

When freopen() function is successful, a pointer to the FILE object is returned. When freopen fails, it changes the global variable errno to indicate the error and returns NULL.

Function Behavior:

When freopen() is invoked, it performs several actions:

  1. Closes the Existing File: Before doing anything further, the function closes the file connected to the supplied stream. The stream is closed before performing any additional file operations if it is already open.
  2. Opens the New File: After that, it opens the file indicated by the filename in the mode indicated by the mode.
  3. Replaces the Stream: The input or output operations are essentially redirected to the newly opened file, which is connected to the specified stream.

Example - Redirecting Standard Output to a File

Output:

 
This will be written to the file instead of the console.
Another line that goes into the file.   

Explanation:

Using the freopen() function, this C code redirects standard output (stdout) to a file called output.txt. The program initially tries to open the file in write mode; if that doesn't work, an error notice appears and the program terminates. After that, the text is written to the file rather than the console by the printf() operations. The file is closed using fclose() after writing. Next, a final printf() statement is printed to the console, and the stdout is returned to it by opening the console again. This demonstrates how output can be redirected to a file and returned to the terminal.

Example - Redirecting Standard Input to a File

Output:

 
Error opening the file: No such file or directory   

Explanation:

This C program demonstrates how to redirect standard input (stdin) from a file using freopen(). The input.txt file is opened first, and stdin is redirected to read from it. After that, the program scans the file line by line, counting as it proceeds, and prints the line number for each line. After file processing, it gives the total number of lines read and determines whether any were. This demonstrates how freopen() may be used for multiple operations on the same file by closing stdin and then reopening the file to read the first line once more. It closes the file once more in the end. For file operations, error handling is integrated to ensure that any issues are reported and handled properly.

Practical Uses

  1. Debugging and Testing: Since freopen() doesn't significantly change program code, it makes it possible to test how programs handle file input and output while they're being developed. This is useful for automated testing and debugging.
  2. Log Management: To assist with debugging and error logging in production environments, redirecting stderr to a file could help capture error messages.

Next TopicC17-standards