codescracker


c

C freopen()



« Previous Function Next Function »


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

#include<stdio.h>
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

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void main()
{
	clrscr();
	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");
		getch();
		exit(1);
	}
	printf("This will be written to the file OUT");
	fclose(fp);
	getch();
}

« Previous Function Next Function »



Tools
Calculator

Quick Links
Signup - Login - Give Online Test