C++ freopen()

The freopen() function is defined in <cstdio> header file.

freopen() prototype

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

The freopen function first attempts to close the file opened using stream. After the file is closed, it attempts to open the filename specified by the argument filename (if it is not null) in the mode specified by the argument mode. Finally it associates the file with the file stream stream.

If filename is a null pointer, the freopen() function attempts to reopen the file that is already associated with stream.


freopen() Parameters

  • filename: New file to open.
  • mode: Mode to open the file with. Different types of file access mode are as follows:
Different modes of file operation
File Access Mode Interpretation If file exists If file doesn't exist
"r" Opens the file in read mode Read from start Error
"w" Opens the file in write mode Erase all the contents Create new file
"a" Opens the file in append mode Start writing from the end Create new file
"r+" Opens the file in read and write mode Read from start Error
"w+" Opens the file in read and write mode Erase all the contents Create new file
"a+" Opens the file in read and write mode Start writing from the end Create new file
  • stream: The file stream to associate filename to.

freopen() Return value

The freopen() function returns:

  • stream on success.
  • NULL on failure.

Example: How freopen() function works?

#include <cstdio>
#include <cstdlib>

int main()
{
	FILE* fp = fopen("test1.txt","w");
	fprintf(fp,"%s","This is written to test1.txt");

	if (freopen("test2.txt","w",fp))
		fprintf(fp,"%s","This is written to test2.txt");
	else
	{
		printf("freopen failed");
		exit(1);
	}

	fclose(fp);
	return 0;
}

When you run the program:

The following will be written to test1.txt:
This is written to test1.txt
The following will be written to test2.txt:
This is written to test2.txt

Also Read:

Did you find this article helpful?

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges