Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

C Library Function - freopen()

C Library Function - freopen()

C Standard Library - <stdio.h> C Standard Library -

Description

C Library Function **FILE *freopen(const char *filename, const char mode, FILE stream) Associate a new filename filename with the given open stream stream , while closing the old file in the stream.

Declaration

Below is the declaration of the freopen() function.



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

Parameters

Mode Description
"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 contents are deleted and the file is treated as a new empty file.
"a" Append to a file. Write operations append data to the end of the file. If the file does not exist, it is created.
"r+" Open a file for updating, both reading and writing. The file must exist.
"w+" Create an empty file for reading and writing.
"a+" Open a file for reading and appending.

Return Value

If the file is opened successfully, the function returns a pointer to the object identifying the stream. Otherwise, it returns a null pointer.

Example

The following example demonstrates the use of the freopen() function.



#include 



int main ()

{

   FILE *fp;



   printf("该文本重定向到 stdout\n");



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



   printf("该文本重定向到 file.txt\n");



   fclose(fp);

   

   return(0);

}

Let's compile and run the above program; this will send the following lines to standard output STDOUT, because initially we did not open standard output:



该文本重定向到 stdout

When calling freopen() After that, it associates standard output STDOUT with the file file.txt, so whatever we write to standard output STDOUT will be written to file.txt, and the file file.txt will have the following contents.



该文本重定向到 file.txt

Now let us use the following program to view the content of the file above:



#include 



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 Standard Library -