It is necessary to keep data in the permanent storage because it is difficult to handle the large volume of data by programs and after execution of program is over all the entered data will be lost because, the data stored in the variables are temporary.
C supports the concept of file through which the data can be stored in the disk or secondary storage device. So the data can be read when required. A file is a collection of data or text, placed on the disk.
There are two types of files- sequential file and random access file. In sequential file, data are kept sequential. As example if we want to access the forty fourth record, then first forty three records should be read sequentially to reach the forty fourth record. In the record access file, the data can be accessed and processed randomly i.e in this case the forty fourth record can be accessed directly. It takes less time than the sequential file.
Hence depending up on the method of accessing the data stored ,there are two types of files.
- Sequential file
- Random access file
1.Sequential File: In this type of files data is kept in
sequential order if we want to read the last record of the
file,we need to read all records before that record so it takes
2.Random access Files: In this type of files data can be read and modified randomly .If we want to read the last record we can read it directly.It takes less time when compared to sequential file.
The steps for file operation in C programming are as follows:
- Open a file.
- Read the fie or write data in the file.
- Close the file.
Opening of a File
When we store a record in the file then at first we need a
temporary area in memory where we store the data/records then we
transfer it to file. For storing these records in the memory, we
use the pointer which points the starting address where the
data/record is stored. We write this as
Here p is a pointer of file type. For declaring to the file type pointer, it is necessary to write FILE in capital and then pointer variable name.
For opening a file we use the library function fopen (). First we declare pointer variable and fopen () as file type pointer. We write this as-
FILE *p, fopen ();
Then p=fopen ("filename"," mode");
Here filename is the name of data file where data/record is stored. Mode decides which operation (read, write or append) is to be performed with data file.
TYPES OF FILES
There are 2 kinds of files in which data can be stored in 2 ways
either in characters coded in their ASCII character set or in
binary format. They are
- Text Files.
- Binary Files