logo
Opening a file In C Language
C communicates with files using a new data type called a file pointer. This type is defined within stdio.h, and written as FILE *. A file pointer called output_file is declared in a statement like
Syntax: FILE *output_file; 

 If we want to store data in a file into the secondary memory, we must specify certain things about the file to the operating system. They include the filename, data structure…
The general format of the function used for opening a file is 

Syntax :
*fp = FILE *fopen(const char *filename, const char *mode);

Here filename is the name of the file to be opened and mode specifies the purpose of opening the file. Mode can be of following types,

*fp is the FILE pointer (FILE *fp), which will hold the reference to the opened(or created) file.
Mode description
r opens a text file in reading mode
w opens or create a text file in writing mode.
r+ opens a text file in append mode
opens a text file in both reading and writing mode
w+ opens a text file in both reading and writing mode
a+ opens a text file in both reading and writing mode
rb opens a binary file in reading mode
wb opens or create a binary file in writing mode
ab opens a binary file in append mode
rb+ opens a binary file in both reading and writing mode
wb+ opens a binary file in both reading and writing mode
ab+ opens a binary file in both reading and writing mode
Return value :

C open function returns NULL in case of 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 file called fileName.txt

• The “w” means that the file is being opened for writing, and if the file does not exist then new file will be created.