Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C

freopen — C23 stream function

`freopen(filename, mode, stream)` from `<stdio.h>` closes the file associated with a stream and reassociates the same `FILE` object with the file and mode named by its arguments. It returns `stream` on success or null on failure.

Version: C23

Syntax

FILE *freopen(const char * restrict filename, const char * restrict mode, FILE * restrict stream);

freopen(filename, mode, stream) from <stdio.h> closes the file associated with a stream and reassociates the same FILE object with the file and mode named by its arguments. It returns stream on success or null on failure.

The example first creates a named file for output, writes 42, then calls freopen(name, "r", stream) and reads the value. Output 1 42 demonstrates successful reopening of the same stream in a different mode.

Errors while closing the old file are ignored, and after a failed freopen the original stream is closed and must not be used. With filename == NULL, the function attempts to change the mode of the file whose name is already associated with the stream; the implementation defines which mode changes are permitted and under what circumstances. Test the return before I/O; w can truncate and a appends.

Examples

#include <stdio.h>
int main(void){const char *name="c_ref_21_freopen.tmp";FILE *stream=fopen(name,"w");if(!stream)return 1;if(fputs("42",stream)==EOF){fclose(stream);remove(name);return 1;}stream=freopen(name,"r",stream);if(!stream){remove(name);return 1;}int value=0,ok=fscanf(stream,"%d",&value)==1;int closed=fclose(stream),removed=remove(name);printf("%d %d\n",ok,value);return closed==0&&removed==0?0:1;}

Result

1 42

The example first creates a named file for output, writes `42`, then calls `freopen(name, "r", stream)` and reads the value. Output `1 42` demonstrates successful reopening of the same stream in a different mode.

Sources