<cstdio>
FILE * freopen ( const char * filename, const char * mode, FILE * stream );
Reopen stream with different file or mode
freopen first tries to close any file already associated with the stream given as third parameter and disassociates it.
Then, whether that stream was successfuly closed or not, freopen opens the file whose name is passed in the first parameter, filename, and associates it with the specified stream just as fopen would do using the mode value specified as the second parameter.
This function is specially useful for redirecting predefined streams like stdin, stdout and stderr to specific files (see the example below).
Parameters
- filename
- C string containing the name of the file to be opened. This parameter must follow the file specifications of the running environment and can include a path if the system supports it.
If this parameter is a null pointer, the function attemps to change the mode of the stream specified as third parater to the one specified in the mode parameter, as if the file name currently associated with that stream had been used.
- mode
- C string containing the file access modes. It can be:
"r" | Open a file for reading. The file must exist. |
"w" | Create an empty file for writing. If a file with the same name already exists its content is erased and the file is treated as a new empty file. |
"a" | Append to a file. Writing operations append data at the end of the file. The file is created if it does not exist. |
"r+" | Open a file for update both reading and writing. The file must exist. |
"w+" | Create an empty file for both reading and writing. If a file with the same name already exists its content is erased and the file is treated as a new empty file. |
"a+" | Open a file for reading and appending. All writing operations are performed at the end of the file, protecting the previous content to be overwritten. You can reposition (fseek, rewind) the internal pointer to anywhere in the file for reading, but writing operations will move it back to the end of file. The file is created if it does not exist. |
An additional b is used to specify the file is to be reopened in binary mode. For more details on these modes, refer to fopen.
- stream
- pointer to a FILE object that identifies the stream to be reopened.
Return Value
If the file was succesfully reopened, the function returns a pointer to an object identifying the stream. Otherwise, a null pointer is returned.
Example
1 2 3 4 5 6 7 8 9 10
|
/* freopen example: redirecting stdout */
#include <stdio.h>
int main ()
{
freopen ("myfile.txt","w",stdout);
printf ("This sentence is redirected to a file.");
fclose (stdout);
return 0;
}
|
This sample code redirects the output that would normally go to the standard output to a file called myfile.txt, that after this program is executed contains:
This sentence is redirected to a file.
See also
fopen | Open file (function) |
|