C freopen()

The freopen() function associates an existing stream with a different file. The end-of-file and the error flags are cleared in the process. The new name of the file is pointed to by fname, the access mode is pointed to by mode, and the stream to be reassigned is pointed to by stream. The mode parameter uses the same format as fopen().

freopen() Syntax

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

When freopen() function is called, then it first tries to close a file that may currently be associated with stream. However, if the attempt to close the file fails, then the freopen() function still continues to open the other file.

On success, the freopen() function returns a pointer to stream, otherwise it returns null pointer.

freopen() Example

Following c program uses freopen() function to redirect the stream stdout to the file called OUT. Because the printf() writes to the stdout, the first message is displayed on the screen and the second is written to the disk file:

Note : The main uses of freopen() function is to redirect the system-defined files stdin, stdout, and the stderr to some other file

void main()
	FILE *fp;
	printf("This will display on the screen\n");
	if((fp=freopen("OUT", "w", stdout))==NULL)
		printf("Error in opening the file..!!\n");
		printf("Press any key to exit..\n");
	printf("This will be written to the file OUT");

C Online Test

« Previous Function Next Function »

Like/Share Us on Facebook 😋