freopen
FILE * freopen (const char * filename , const char * mode , FILE * stream); | stdio.h |
cplusplus.com |
Reopen a stream with a different file and mode.
freopen first tries to close any file already open associated
with the given stream.
Then, whether the stream was closed or not, freopen opens
the file which name is pointed by filename string and
associates it with the specified stream.
The operations allowed to the file returned are defined by the
mode parameter as in fopen function.
This function is specially useful for redirecting system defined streams
stdin, stdout and stderr to other files.
Parameters.
Open a file for reading. The file must exist. | |
Create an empty file for writing. If a file with the same name already exists its content is erased. | |
Append to a file. Writing operations append data at the end of the file. The file is created if it doesn't exist. | |
Open a file for reading and writing. The file must exist. | |
Create an empty file for reading and writing. If a file with the same name already exists its content is erased before it is opened. | |
Open a file for reading and appending. All writing operations are done at the end of the file protecting the previous content to be overwritten. You can reposition (fseek, rewind) the pointer to anywhere in the file for reading, but writing operations will move back to the end of file. The file is created if it doesn't exist. |
Text mode. In text mode the end of file is assumed to be at first Ctrl-Z character. Some conversions can occur reading and writing with End Of Line / Feedback characters depending on your compiler and your Operating System. | |
Binary mode. End of file is reached at last byte of the file. No conversions. |
Return Value.
If the file has been succesfully reopened the function returns a pointer to the file.
Otherwise a NULL pointer is returned.
Portability.
Defined in ANSI-C.
Example.
/* freopen example: redirecting stdout */
#include <stdio.h>
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 normally would go to
standard output to a file called myfile.txt, that after
this program is executed contains:
This sentence is redirected to a file.