C library functions -fopen()

C Standard Library - <stdio.h>

Description

C Library FunctionsFILE *fopen(const char *filename, const char *mode)using the given modemodeOpenfilenamethe file pointed to.

Declaration

Below is the declaration of the fopen() function.

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

Parameter

  • filename-- A string representing the name of the file to open.
  • mode-- A string representing the file access mode, which can be one of the values in the following table:
ModeDescription
"r" Opens a file for reading. The file must exist.
"w" Creates an empty file for writing. If the filename is the same as an existing file, the existing file's contents are deleted, and the file is treated as a new empty file.
"a" Appends 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, readable and writable. The file must exist.
"w+" Create an empty file for 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 the error.

Example

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

Example

#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 us compile and run the above program, which will create a file with the following content.file.txt:

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>

other extensions