freopen() — Redirect Open Files
Format
#include <stdio.h>
FILE *freopen(const char *filename, const char *mode, FILE *stream);
Language Level
ANSI
Threadsafe
Yes
Description
The freopen()
function
closes the file that is currently associated with stream and
reassigns stream to the file that is specified
by filename. The freopen()
function
opens the new file associated with stream with
the given mode, which is a character string
specifying the type of access requested for the file. You can also
use the freopen()
function
to redirect the standard stream files stdin
, stdout
, and stderr
to
files that you specify.
For database files, if filename is
an empty string, the freopen()
function
closes and reopens the stream to the new open mode, rather than reassigning
it to a new file or device. You can use the freopen()
function
with no file name specified to change the mode of a standard stream
from text to binary without redirecting the stream, for example:
fp = freopen("", "rb", stdin);
You can use the same method to change the mode from binary back to text.
You cannot use the freopen()
function
with filename as an empty string in modules
created with SYSIFCOPT(*IFSIO).
Return Value
The freopen()
function
returns a pointer to the newly opened stream. If an error occurs,
the freopen()
function
closes the original file and returns a NULL pointer value.
- Value
- Meaning
- EBADF
- The file pointer or descriptor is not valid.
- EBADMODE
- The file mode that is specified is not valid.
- EBADNAME
- The file name that is specified is not valid.
- ENOENT
- No file or library.
- ENOTOPEN
- The file is not open.
- EIOERROR
- A non-recoverable I/O error occurred.
- EIORECERR
- A recoverable I/O error occurred.
Example
#include <stdio.h>
#define MAX_LEN 100
int main(void)
{
FILE *stream, *stream1, *stream2;
char line[MAX_LEN], *result;
int i;
stream = fopen("mylib/myfile","r");
if ((result = fgets(line,MAX_LEN,stream)) != NULL)
printf("The string is %s\n", result);
/* Change all spaces in the line to '*'. */
for (i=0; i<=sizeof(line); i++)
if (line[i] == ' ')
line[i] = '*';
stream1 = stream;
stream2 = freopen("", "w+", stream1);
fputs( line, stream2 );
fclose( stream2);
}