C fopen()

The fopen() function defined in the stdio.h header file. It helps to open the file specified in the argument filename in a given mode.


FILE *fopen(const char *filename, const char *mode); #where filename should be a string

 

fopen() Parameters: 

The fopen() function takes two parameters. The file open modes are the following types.

  • r  : Opens a file for reading. The file must exist.
  • w : Creates an empty file for writing. If the same file name exists, its content is erased and is considered as a new empty file.
  • a  : Appends to a file. Writing operations, append data at the end of the file
  • 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.
Parameter Description Required / Optional
filename the name of the file to be opened Required
mode           the file access modes  Required 

fopen() Return Value

The return value of fopen() function is a file pointer. Else it returns the NULL, and for indicating the error global variable errno is set. 

 

Input Return Value
if execution succeeds file pointer
if execution not succeed NULL

Examples of fopen() 

Example 1: Working of fopen() function in C?


#include <stdio.h>

int main () {
   FILE * pnt;

   pnt = fopen ("myfile.txt", "w+");
   fprintf(pnt, "%s %s %s %d", "Hii", "all", "I am", 2000);
   
   fclose(pnt);
   
   return(0);
}

Output:


Hii all I am 2000

Example 2: How fopen() works in C?


#include <stdio.h>

int main()
{
 
    // pointer to FILE
    FILE* pnt;
 
  
    pnt = fopen("testfile.txt", "w+");
 
    // adds content to the file
    fprintf(pnt, "%s %s %s", "C Program",
            "tutorials");
 
    // closes the file 
    fclose(pnt);
 
    return 0;
}

Output:


C Program tutorials