C fopen

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

The basic format of fopen is:

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

Parameters

  • 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:

ModeDescription
rOpens an existing text file.
wOpens a text file for writing if the file doesn't exist then a new file is created.
aOpens 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.

Example:
#include<stdio.h>

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.

Scroll Back to Top