Latest web development tutorials

C library functions - fopen ()

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

description

C library functionsFILE * fopen (const char * filename , const char * mode) with the given filenamepatternmodeopens the file pointed to.

statement

Here is the fopen () function's declaration.

FILE *fopen(const char *filename, const char *mode)

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+" 打开一个用于读取和追加的文件。

return value

This function returns a FILE pointer. Otherwise, it returns NULL, and the global variable errno to identify the error.

Examples

The following example demonstrates the fopen () function is used.

#include <stdio.h>
#include <stdlib.h>

int main()
{
   FILE * fp;

   fp = fopen ("file.txt", "w+");
   fprintf(fp, "%s %s %s %d", "We", "are", "in", 2014);
   
   fclose(fp);
   
   return(0);
}

Let's compile and run the above program, which will create a filefile.txt with a look at the contents:

We are in 2014

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>