Introduction
A file is a space in the memory where we can store the data. A file can be a text file or a binary file. It always represents a sequence of bytes. Whenever a program terminates(reasons can be electricity cut, system shut down, etc.), the entire data gets lost. We can protect our data from getting lost by storing it in the file. We can treat files as a container to store our data.
Recommended Topic, Sum of Digits in C, C Static Function.
Let us now see various operations we can perform on a File.
Opening Files
In order to create a new file or open any of the existing files, we can use the fopen() function. Calling this function will create an object of the type FILE. This object would contain all the necessary information to control the stream of data.
Syntax:-
FILE *fopen( const char * filename, const char * mode );
fileName: It is a String literal that specifies the file name.
mode: It is a mode of access. There are different types of modes as listed below.
| S. No. | Mode | Description |
| 1 | r | This mode is used to open a file for reading the data. |
| 2 | w | This mode is used to open a file and write data to it. If no such file exists, then a new file is created. It starts writing the data from the beginning of the file. |
| 3 | a | This mode is used to open a file and write the data to it in an appending mode. If no such file exists, then a new file is created. It starts appending the new data to the old data of the file. |
| 4 | r+ | This mode is used to open a file for both reading and writing of data. |
| 5 | w+ | This mode is used to open a file for both reading and writing of data. It truncates the files to zero length if it exists, else creates a new file. |
| 6 | a+ | This mode is used to open a file for both reading and writing. It creates a new file if it does not exist. It reads from the starting and appends(write) to the end of the old data of the file. |
All of the above modes are used to access a text file.
Modes used to access a Binary file with the same functionalities are:-
- rb
- wb
- ab
- rb+
- r+b
- wb+
- w+b
- ab+
- a+b




