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:
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.
fopen() access mode can be one of the following values:
|It opens an existing text file.
|It opens a text file for writing; a new file is created if the file doesn't exist.
|It opens a text file for appending(writing at the end of an existing file) and creates the file if it does not exist.
|It opens a text file for reading and writing.
|It opens a text file for reading and writing, creates the file if it does not exist, and empties it if it already exists.
|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.
fopen() function returns
NULL in case of a failure and returns a FILE stream pointer on success.
fp = fopen("fileName.txt","w");
- The above example will create a file called fileName.txt.
- Here in the above program,
wmeans that the file is being opened for writing, and if the file does not exist, a new file will be created.