The name of the file to open, as a null-terminated string
2nd Parameter Type : const char *
Pointer to read-only string
2nd Parameter
The file access mode, such as 'r', 'w', or 'a', optionally combined with 'b' for binary mode
3rd Parameter Type : FILE *
Pointer to FILE structure for file operations
3rd Parameter
Pointer to an existing file stream to be reassigned to the new file
Read more about parameters of freopen in parameters section
The freopenfunction in C language Reopens the file stream with a different file or mode.
The freopen function associates a new filename with the given open stream and at the same time closes the old file in the stream. This function is particularly useful for redirecting the standard streams (stdin, stdout, stderr) to files. If the operation fails, the original stream is closed. When successful, freopen clears the error and end-of-file indicators for the stream.
The freopenfunction takes 3
parameters:
•
const char * `filename`: The name of the file to open, as a null-terminated string
•
const char * `mode`: The file access mode, such as 'r', 'w', or 'a', optionally combined with 'b' for binary mode
•
FILE * `stream`: Pointer to an existing file stream to be reassigned to the new file
Closes the file associated with `stream` and reopens it as the file specified by `filename`, using the given `mode`. Returns a pointer to the reassigned `FILE` object on success or `NULL` on failure.
The freopen function return value :
Returns a pointer to the newly associated stream
If the operation fails, NULL is returned, and the original stream is closed
Output
This example demonstrates how to use `freopen` to redirect stdout to a file. It first prints to the console, then redirects stdout to a file, prints to the file, and finally restores stdout to print to the console again.