C fopen is a C library function used to open an existing file or create a new file.

The basic format of fopen is:

FILE *fopen( const char * filePath, const char * mode );


  • filePath: The first argument is a pointer to a string containing the name of the file to be opened.
  • mode: The second argument is an access mode.

C fopen() access mode can be one of the following values:

Mode Description
r Opens an existing text file.
w Opens a text file for writing if the file doesn't exist then a new file is created.
a Opens a text file for appending(writing at the end of existing file) and create the file if it does not exist.
r+ Opens a text file for reading and writing.
w+ Open for reading and writing and create the file if it does not exist. If the file exists then make it blank.
a+ Open for reading and appending and create the file if it does not exist. The reading will start from the beginning, but writing can only be appended.

Return Value

C fopen function returns NULL in case of a failure and returns a FILE stream pointer on success.


int main()
    FILE *fp;
    fp = fopen("fileName.txt","w");
    return 0; 
  • The above example will create a file called fileName.txt.
  • The w means that the file is being opened for writing, and if the file does not exist then the new file will be created.