Easy Tutorial
❮ C Exercise Example77 C Function Acos ❯

C Library Function - freopen()

C Standard Library - <stdio.h>

Description

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

Declaration

Here is the declaration for the freopen() function.

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

Parameters

Mode Description
"r" Opens a file for reading. The file must exist.
"w" Creates an empty file for writing. If a file with the same name already exists, its content is erased and the file is treated as a new empty file.
"a" Appends to a file. Writing operations append data at the end of the file. The file is created if it does not exist.
"r+" Opens a file for both reading and writing. The file must exist.
"w+" Creates an empty file for both reading and writing.
"a+" Opens a file for reading and appending.

Return Value

On success, the function returns a pointer to an object that identifies the stream. Otherwise, a null pointer is returned.

Example

The following example demonstrates the use of the 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's compile and run the above program. This will send the following line to the standard output STDOUT, as initially, we did not open the standard output:

This text is redirected to stdout

After calling freopen(), it associates the standard output STDOUT with the file file.txt. Anything we write to the standard output STDOUT will be written to file.txt, so the file file.txt will have the following content.

This text is redirected to file.txt

Now, let's use the following program to view the content of the above file:

#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);
}

C Standard Library - <stdio.h>

❮ C Exercise Example77 C Function Acos ❯