C++ Standard Library C++ STL Library

C++ <cstdio> - freopen() Function



The C++ <cstdio> fopen() function reuses stream to either open the file specified by filename or to change its access mode.

If filename is specified, the function attempts to open the file specified by filename using mode as if by using fopen() function, and associates that file with the file stream pointed to by stream.

If filename is a null pointer, then the function attempts to reopen the file which is already associated with stream to change the mode of the stream.

The error indicator and EOF indicator are automatically cleared.

Syntax

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

Parameters

filename Specify file name to associate the file stream to. It can include a path (if supported by the system).
mode Specify C string containing a file access mode. See the table below for more details.
stream Specify pointer to a FILE object that identifies the stream to be reopened.

ModesDescriptionAction: If file existsAction: If file does not exist
"r" Read: open a file for reading Read from startFailure to open
"w" Write: create a file for writing Delete contentsCreate new
"a" Append: append to a file Write to endCreate new
"r+" Read extended: open a file for read/write Read from startError
"w+" Write extended: create a file for read/write Delete contentsCreate new
"a+" Append extended: open a file for read/write Write to endCreate new

  • The above discussed mode specifiers opens a file as a text file. To open a file as a binary file, a "b" character has to be included in the mode string. This additional "b" character can either be appended at the end of the string ("rb", "wb", "ab" OR "r+b", "w+b", "a+b") or be inserted between the letter and the "+" sign for the mixed modes ("rb+", "wb+", "ab+").
  • File access mode flag "x" can optionally be appended to "w" or "w+" specifiers. This flag forces the function to fail if the file exists, instead of overwriting it (since C++17).
  • The behavior is undefined if the mode is not one of the strings listed above. Some implementations define additional supported modes.

Return Value

On success, returns stream. On failure, returns a null pointer.

Example:

In the example below, stdout is redirected to a file called test.txt.

#include <cstdio>
 
int main (){
  FILE *pFile = freopen("test.txt", "w", stdout);
  
  printf("stdout is redirected to test.txt.");

  fclose(stdout);

  return 0;
}

After executing the above code successfully, file text.txt will contain:

stdout is redirected to test.txt.

❮ C++ <cstdio> Library