C Language freopen Function Explained

The freopen function is used to reopen a file and associate it with a specified stream. Reopening a file can be used to change the input or output file of a stream, or to reopen a file after it has been closed.

The function prototype is:

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

The function returns a pointer to the new file stream, with the filename as the name of the file to be reopened, mode as the specified access mode when opening the file, and stream as the stream to be reassigned.

For example, if you want to redirect the standard input stream stdin to the file input.txt, you can use the following code:

freopen("input.txt", "r", stdin);

From now on, all standard input operations will read data from the input.txt file.

bannerAds