fopen() function in c – fopen C Library Function

fopen() function in c: The function FILE *fopen(const char *filename, const char *mode); opens the file whose name is given in the filename argument and associate it with a stream and return a FILE pointer to be used in any future I/O operations on this stream. The fopen function opens a stream in a particular mode, which defines the operations that are allowed on the stream.

Various modes for opening a stream

Mode Description
“r” To read a file. Opens a file for reading. The file must exist.
“w” To write on a file. Creates an empty file for writing. If a file already exists with same name, its content is removed and the file is considered as a new empty file.
“a” To append data at the end of file. The file is created if it does not exist.
“r+” To read and write on an existing file. Opens a file to update both reading and writing. The file must exist.
“w+” To create a new file for reading and writing.
“a+” To read and append data on a file.

Function prototype of fopen

FILE *fopen(const char *filename, const char *mode);
  • filename : This is a null-terminated string containing the name of the file to be opened.
  • mode : This is a null-terminated string containing a file access mode.

Return value of fopen

Fopen c: On success, this function returns a FILE pointer. Otherwise, NULL is returned and the global variable errno is set to indicate the error.

C program using fopen function

Fopen in c: The following program shows the use of fopen function to open a text file in read mode.

fopen C Library Function

#include <stdio.h>
 
int main(){
   FILE *file;
   int ch;
    
   /* Open a file for reading */
   file = fopen("textFile.txt","r");
   if(file == NULL){
      perror("Error: Unable to open a file");
   } else {
       while(!feof(file)){
          ch = fgetc(file);
          printf("%c", ch);
       }
       fclose(file);
   }
    
   return(0);
}

Output

fopen C Standard library function