File Handling in C
We frequently use files for storing information which can be processed by our programs. In order to store information permanently and retrieve it we need to use files. Files are not only used for data. Our programs are also stored in files. The editor which you use to enter your program and save it, simply manipulates files for you.The Unix commands cat, cp, cmp are all programs which process your files.
In order to use files we have to learn about File I/O i.e. how to write information to a file and how to read information from a file. We will see that file I/O is almost identical to the terminal I/O that we have being using so far.
The primary difference between manipulating files and doing terminal I/O is that we must specify in our programs which files we wish to use. As you know, you can have many files on your disk. If you wish to use a file in your programs, then you must specify which file or files you wish to use. Specifying the file you wish to use is referred to as opening the file. When you open a file you must also specify what you wish to do with it i.e. Read from the file, Write to the file, or both. Because you may use a number of different files in your program, you must specify when reading or writing which file you wish to use. This is accomplished by using a variable called a file pointer. Every file you open has its own file pointer variable. When you wish to write to a file you specify the file by using its file pointer variable. You declare these file pointer variables as follows:
FILE *fopen(), *fp1, *fp2, *fp3;
The variables fp1, fp2, fp3 are file pointers. You may use any name you wish. The file <stdio.h> contains declarations for the Standard I/O library and should always be included at the very beginning of C programs using files. Constants such as FILE, EOF and NULL are defined in <stdio.h>. You should note that a file pointer is simply a variable like an integer or character. It does not point to a file or the data in a file. It is simply used to indicate which file your I/O operation refers to. A file number is used in the Basic language and a unit number is used in Fortran for the same purpose. The function fopen is one of the Standard Library functions and returns a file pointer which you use to refer to the file you have opened e.g.
fp = fopen( "ccplusplus.com", "r") ;
The above statement opens a file called ccplusplus.com for reading and associates the file pointer fp with the file. When we wish to access this file for I/O, we use the file pointer variable fp to refer to it.
You can have up to about 20 files open in your program - you need one file pointer for each file you intend to use.
I am explaining all the concepts of file handling using all the I/O operations. Go through the below link to understand all of them clearly with the sample codes provide.