The freopen
function closes the old file in the given open stream and associates a new filename
with this stream. It is written as follows:
FILE *freopen(const char *filename, const char *mode, FILE *stream)
filename
- the name of the file to be opened. This is a C string
.
mode
- C string
containing a file access mode. Different file access modes are mentioned below:
Mode | Description |
---|---|
“r” | Opens a file to be read. This file should already have been created. |
“w” | Creates an empty file that can be written to. If there is another file with the same name,then that is eradicated and this file is the empty file. |
“a” | Adds contents to the end of a file. In case the file is not created already, then a new file is created first. |
“r+” | Opens a file to update it (both reading and writing). The file should already have been created. |
“w+” | Creates a new empty file and opens it for update (both reading and writing). IIf there is another file with the same name,then that is eradicated and this file is the empty file… |
“a+” | Opens a file for update (both reading and appending). |
If the file was re-opened successfully, the function returns a pointer passed as the parameter stream
that identifies the reopened stream
. Otherwise, null pointer
is returned.
The following code shows the usage of the freopen
function. After freopen
is called, stdout
is associated with the file sampleFile.txt
. Therefore, whatever is written at stdout
is written to sampleFile.txt
:
#include <stdio.h>int main () {freopen ("sampleFile.txt","w",stdout);printf ("This sentence will be moved to a file.");fclose (stdout);return(0);}
After the execution of the code above, sampleFile.txt
will contain the string at line 5.
Free Resources