C fopen is a C library function used to open an existing file or create a new file. This tutorial guides you on how to use the fopen() function in the C program.



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:

Mode Description
r It opens an existing text file.
w It opens a text file for writing; a new file is created if the file doesn't exist.
a It opens a text file for appending(writing at the end of an existing file) and creates the file if it does not exist.
r+ It opens a text file for reading and writing.
w+ It opens a text file for reading and writing, creates the file if it does not exist, and empties it if it already exists.
a+ It opens a text file for reading and appending and creates the file if it doesn't exist. Reading starts from the beginning, but writing can only append.

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.
  • Here in the above program, w means that the file is being opened for writing, and if the file does not exist, a new file will be created.


Found This Page Useful? Share It!
Get the Latest Tutorials and Updates
Join us on Telegram