6.18.23 freopen Function
Reassigns an existing stream to a new file.
Include
<stdio.h>
Prototype
FILE *freopen(const char * restrict filename, const char * restrict
mode, FILE * restrict stream);
Arguments
filename
- name of the new file
mode
- type of access permitted
stream
- pointer to the currently open stream
Return Value
Returns a pointer to the new open file. If the function fails a null pointer is returned.
Remarks
The function closes the file associated with the stream as though fclose
was called. Then it opens the new file as though fopen
was called.
freopen
will fail if the specified stream is not open. See
fopen
for the possible types of file access.
This function requires a heap.
Example
#include <stdio.h>
int main(void)
{
FILE *myfile1, *myfile2;
int y;
if ((myfile1 = fopen("afile1", "w+")) == NULL)
printf("Cannot open afile1\n");
else
{
printf("afile1 was opened\n");
if ((myfile2 = freopen("afile2", "w+",
myfile1)) == NULL)
{
printf("Cannot open afile2\n");
fclose(myfile1);
}
else
{
printf("afile2 was opened\n");
fclose(myfile2);
}
}
}
Example Output
afile1 was opened
afile2 was opened
Example Explanation
This program uses myfile2
to point to the stream when
freopen
is called, so if an error occurs, myfile1
will still point to the stream and can be closed properly. If the
freopen
call is successful, myfile2
can be used to
close the stream properly.