C library function - freopen()

Advertisements


Description

The C library function FILE *freopen(const char *filename, const char *mode, FILE *stream) associates a new filename with the given open stream and same time closing the old file in stream.

Declaration

Following is the declaration for freopen() function.

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

Parameters

  • filename -- This is the C string containing the name of the file to be opened.

  • mode -- This is the C string containing a file access mode.It includes:

modeDescription
"r" Open a file for reading. The file must exist.
"w" Create an empty file for writing. If a file with the same name already exists its content is erased and the file is considered as a new empty file.
"a" Append to a file. Writing operations append data at the end of the file. The file is created if it does not exist.
"r+" Open a file for update both reading and writing. The file must exist.
"w+" Create an empty file for both reading and writing.
"a+" Open a file for reading and appending.
  • stream -- This is the pointer to a FILE object that identifies the stream to be reopened.

Return Value

If the file was reopened successfully, the function returns a pointer to an object identifying the stream else, null pointer is returned.

Example

The following example shows the usage of freopen() function.

#include <stdio.h>

int main ()
{
   FILE *fp;

   printf("This text is redirected to stdout\n");

   fp = freopen("file.txt", "w+", stdout);

   printf("This text is redirected to file.txt\n");

   fclose(fp);
   
   return(0);
}

Let us compile and run the above program, this will send follwoing line at STDOUT because initially we did not open stdout:

This text is redirected to stdout

After a call to freopen(), it associates STDOUT to file file.txt, so whatever we write at STDOUT that goes inside file.txt. So file file.txt will have following content.

This text is redirected to file.txt

Now let's the content of the above file using the following program:

#include <stdio.h>

int main ()
{
   FILE *fp;
   int c;

   fp = fopen("file.txt","r");
   while(1)
   {
      c = fgetc(fp);
      if( feof(fp) )
      {
          break ;
      }
      printf("%c", c);
   }
   fclose(fp);
   return(0);
}


Advertisements
Advertisements