freopen : <stdio.h> library function

The function FILE *freopen(const char *filename, const char *mode, FILE *stream); reopen stream with different file or mode. It attempts to close any file already associated with stream before opening the file specified by filename.
If filename argument is null pointer, the freopen function attempts to change the mode of the stream.

Various modes of reopening a stream

Mode Description
"r" To read a file. Opens a file for reading. The file must exist.
"w" To write on a file. Creates an empty file for writing. If a file already exists with same name, its content is removed and the file is considered as a new empty file.
"a" To append data at the end of file. The file is created if it does not exist.
"r+" To read and write on an existing file. Opens a file to update both reading and writing. The file must exist.
"w+" To create a new file for reading and writing.
"a+" To read and append data on a file.

Function prototype of freopen

FILE *freopen(const char *filename, const char *mode, FILE *stream);
  • filename : This is null terminated string containing the name of the file to be opened.
  • mode : This is a null-terminated string containing a file access mode.
  • stream : This is a pointer to a FILE object which identifies a stream.

Return value of freopen

On success, this function returns the passed FILE pointer stream. Otherwise, null pointer is returned and the global variable errno is set to indicate the error.

C program to show the use of freopen function

The following program shows the use of freopen function to redirect content of stdout stream to a text file.

#include <stdio.h>

int main ()
{
  FILE *file;
  
  file = freopen("textFile.txt","w+",stdout);
  printf("This sentence will not get printed on screen\n");
  fclose(file);
  
  return 0;
}

Program Output Above program will create a textfile with "This sentence will not get printed on screen" string. It will redirect all content from stdout stream to a text file.