C library function - fopen()


Advertisements


Description

The C library function FILE *fopen(const char *filename, const char *mode) opens the filename pointed to, by filename using the given mode.

Declaration

Following is the declaration for fopen() function.

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

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 −

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 considered 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 to update 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

This function returns a FILE pointer. Otherwise, NULL is returned and the global variable errno is set to indicate the error.

Example

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

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

int main()
{
   FILE * fp;

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

Let us compile and run the above program that will create a file file.txt with the following content −

We are in 2012

Now let us see 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);
}

Let us compile and run the above program to produce the following result −

We are in 2012

stdio_h.htm

Advertisements