C Library - freopen() function



The C library FILE *freopen(const char *filename, const char *mode, FILE *stream) function associates a new filename with the given open stream and at the same time closes the old file in the stream.

Syntax

Following is the C library syntax of the freopen() function −

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

Parameters

Below is the list of parameter that can be used within the parenthesis of C library function freopen() −

  • filename : A pointer to a null-terminated string that specifies the name of the file to be opened. If filename is NULL, the freopen function attempts to change the mode of the existing stream.
  • mode :A pointer to a null-terminated string that specifies the mode in which the file is to be opened. This mode string can be:
    • r :Open for reading.
    • w :Open for writing (truncates file to zero length).
    • a :Open for appending (writes are added to the end of the file).
    • r+ :Open for reading and writing.
    • w+ :Open for reading and writing (truncates file to zero length).
    • a+ :Open for reading and writing (writes are added to the end of the file).
  • stream :A pointer to a FILE object that specifies the stream to be reopened. This stream is usually associated with a file, but it can also be standard input, output, or error streams (stdin, stdout, or stderr).

Return Value

On success, freopen returns a pointer to the FILE object. On failure, it returns NULL and sets the global variable errno to indicate the error.

Example 1: Redirecting Standard Output to a File

This example redirects the standard output (stdout) to a file named output.txt.

Below is the illustration of C library freopen() function −

#include <stdio.h>

int main() {
   FILE *fp = freopen("output.txt", "w", stdout);
   if (fp == NULL) {
       perror("freopen");
       return 1;
   }
   printf("This will be written to the file output.txt instead of standard output.\n");
   fclose(fp);
   return 0;
}

Output

The above code produces following result in output.txt file −

This will be written to the file output.txt instead of standard output.

Example 2: Redirecting Standard Input to a File

This example redirects the standard input (stdin) to read from a file named input.txt and prints its contents to standard output.

#include <stdio.h>

int main() {
   FILE *fp = freopen("input.txt", "r", stdin);
   if (fp == NULL) {
       perror("freopen");
       return 1;
   }

   char buffer[100];
   while (fgets(buffer, sizeof(buffer), stdin) != NULL) {
       printf("%s", buffer);
   }

   fclose(fp);
   return 0;
}

Output

After execution of above code, we get the following result o terminal and the content of input.txt remains unchanged:

Line 1: This is the first line.
Line 2: This is the second line.
Advertisements