Latest web development tutorials

C library functions - freopen ()

C standard library - <stdio.h> C standard library - <stdio.h>

description

C library functionsFILE * freopen (const char * filename , const char * mode, FILE * stream) to a new file name filenameflowstreamassociated with the given set of open, while closing the stream of old files.

statement

Here is freopen () function's declaration.

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

parameter

  • filename - This is a C string containing the name of the file you want to open.
  • mode - This is a C string containing the file access mode, the mode is as follows:
模式描述
"r" 打开一个用于读取的文件。该文件必须存在。
"w" 创建一个用于写入的空文件。如果文件名称与已存在的文件相同,则会删除已有文件的内容,文件被视为一个新的空文件。
"a" 追加到一个文件。写操作向文件末尾追加数据。如果文件不存在,则创建文件。
"r+" 打开一个用于更新的文件,可读取也可写入。该文件必须存在。
"w+" 创建一个用于读写的空文件。
"a+" 打开一个用于读取和追加的文件。
  • stream - This is a pointer to FILE pointer to an object, the object identifier FILE is to be re-open the stream.

return value

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

Examples

The following example demonstrates freopen () function is used.

#include <stdio.h>

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, which will send the following lines to the standard output STDOUT, because at first we did not turn on the standard output:

该文本重定向到 stdout

After callingfreopen (), it will be associated to the standard output STDOUT file file.txt,whether we will be in what is written is written to standard output STDOUT file.txt, you will have the following file file.txt contents.

该文本重定向到 file.txt

Now let's use the following procedure to view the contents 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 standard library - <stdio.h>