C examples for stdio.h:freopen
function
<cstdio> <stdio.h>
Reopen stream with different file or mode
FILE * freopen ( const char * filename, const char * mode, FILE * stream );
Parameter | Description |
---|---|
filename | C string containing the file name. |
mode | C string containing a file access mode. |
stream | pointer to a FILE object that identifies the stream to be reopened. |
The mode can be:
Value | Action | Description |
---|---|---|
"r" | read | Open file for reading. The file must exist. |
"w" | write | Create an empty file for writing. If the file already exists, empty the existing file. |
"a" | append | Open file for appending. The file is created if it does not exist. |
"r+" | read/update | Open a file both for input and output. The file must exist. |
"w+" | write/update | Create an empty file and open it both for input and output. If the file already exists, empty the existing file. |
"a+" | append/update | Open a file both for input and output, append to the end of the file. The file is created if it does not exist. |
With the mode specifiers above the file is open as a text file.
In order 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.
It makes the following compound modes: "rb", "wb", "ab", "r+b", "w+b", "a+b") or ("rb+", "wb+", "ab+").
On success, the function returns the pointer for the reopened stream.
Otherwise, a null pointer is returned.
The following code code reopened main.cpp file and redirected stdout:
#include <stdio.h> int main ()// w ww . j a va2 s . co m { freopen ("main.cpp","w",stdout); printf ("This sentence is redirected to a file."); fclose (stdout); return 0; }