C programming stdio.h function - FILE *freopen(const char *filename, const char *mode, FILE *stream)
In C programming, the freopen()
function is defined in the stdio.h
header file and is used to change the file associated with a stream. The function takes the following three arguments:
FILE *freopen(const char *filename, const char *mode, FILE *stream);
The first argument, filename
, is a string that specifies the name of the file to be opened. The second argument, mode
, is a string that specifies the mode in which the file is to be opened. The third argument, stream
, is a pointer to a FILE
object that represents the stream to be redirected.
The freopen()
function closes the file associated with the given stream and opens the new file with the specified mode. The new file becomes associated with the stream and the function returns a pointer to the FILE
object that represents the stream.
Here's an example of how to use freopen()
to redirect the standard output stream to a file:
#include <stdio.h> int main() { FILE *fp; fp = freopen("output.txt", "w", stdout); if (fp == NULL) { printf("Error opening file.\n"); return 1; } printf("This will be written to the file.\n"); fclose(fp); return 0; }
In the above example, the freopen()
function is used to redirect the standard output stream to a file named "output.txt". The stdout
pointer is passed as the third argument to the freopen()
function to specify the standard output stream. The function returns a pointer to the FILE
object that represents the stream, which is assigned to the fp
variable.
After redirecting the standard output stream to the file, any subsequent calls to printf()
or other output functions will write to the file instead of the console. Once the file is no longer needed, it should be closed using the fclose()
function.