Easy Tutorial
❮ C Exercise Example70 C Function Abort ❯

C Library Function - fopen()

C Standard Library - <stdio.h>

Description

The C library function FILE *fopen(const char *filename, const char *mode) opens the file specified by filename with the given mode mode.

Declaration

Here is the declaration for the fopen() function.

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

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

The function returns a FILE pointer. Otherwise, it returns NULL and sets the global variable errno to indicate an error.

Example

The following example demonstrates the use of the 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", 2014);

   fclose(fp);

   return(0);
}

Let's compile and run the above program, which will create a file file.txt with the following content:

We are in 2014

Now let's use the following program 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 Exercise Example70 C Function Abort ❯