Lesson 10: File Management In C.
Prev || Home || Next
Until now, we have been using the functions such as scanf() and printf() to read and write data. These console oriented I/O functions which always use the terminal as the target place. They pose two major problems-
1) It becomes difficult and time consuming to handle large volumes of data through terminals.
2) The entire data is lost when either the program is terminated or the computer is turned off.
It is therefore necessary to use concept of files where data can be stored on the disk and read whenever necessary.
C supports a number of functions that have the ability to perform basic file operations which include-
1) Naming file.
2) Opening file.
3) Reading data from a file.
4) Writing data to a file.
5) Closing a file.
We shall discuss the standard file handling functions that are available in C library.
|foopen()||Creates a new file for use or opens existing file for use|
|fclose()||Closes the file which has been opened for use.|
|getc()||Reads a character from a file.|
|putc()||Writes a character to a file.|
|fprintf()||Writes a set of data values to a file.|
|fscanf()||Reads a set of data values from a file.|
|getw()||Reads an integer from a file.|
|putw()||Writes an integer to a file.|
|fseek()||Set the position to desired point in the file.|
|ftell()||Gives the current position in the file(in terms of bytes from the start).|
|rewind()||Sets the position to the begining of file.|
Defining and Opening a File:
If we want to store data in a file in the secondary memory, following things are to be specified.
1) File name. 2) Data structure. 3) Purpose.
File name may contain a primary name and optional period with extension. Data structure of file is defined as FILE in the library of standard I/O function definition. Therefore, all files will be declared as type FILE before they are usef. File is a defined data type. Following is the general format for declaring and opening a file:
The first statement declares the variable fp as a "pointer to data type FILE". The second statement opens the file named filename and assigns an identifier to the FILE type pointer fp. This pointer which contains all the information about the file is subsequently used as a communication link between system and program.
The second statement also specifies the purpose of opening the file. This is done by mode which can be one of the following:
1) r- opens the file for reading only.
2) w- opens a file foe writing only.
3) a- opens the file for appending(adding) data to it).
Consider the following statement
The file data is openend for reading and result for writing. In case, the result file already exists, its contents are deleted and the file is opened as a new file. In case, data files does notexists, an error will occur will accur. We can open and use .
Closing a file:
After use, file should be closed for many reasons. It takes the following form.
This would close the file associated with the file_pointer. Look at the following segment of a program:
This program opens two files & closes them after all operations on them are complete. Once a file is closed, its file pointer can be used for another file.
Input/Output Operations on Files:
Once a file is opened, reading out of or writing to it is accomplished using the standard I/O fubctions. The getc() & putc() functions are standard I/O functions.
The simpleset file I/O functions are getc() and putc(). These are analogous to getchar() & putchar() functions & handle one character at a time. Assume that a file is opened with mode w & file pointer fp1. Then the statement putc(c,pf1); writes the character contained in variable c to the file associated with FILE pointer fp1. Similarly getc() is used to read character from a file that has been opened in read mode. The statement c=getc(fp2); would read a character from the file whose file pointer has been reached.
Program:- Writing to and reading from a file.
The getw() & putw() functions:
The getw() & putw() are integer-oriented functions. They are similar to getc() & putc() functions and are used to read and to write integer valuyes. The general form is:
printf("Contents of Data File\n\n");
printf("\nContents of ODD file\n");
printf("\nContent of EVEN number\n");
The fprintf() & fscanf() Functions:
So far we have seen functions which can handle only one character or integer at a time. There are two functions fprintf() and fscanf() which are indentical to printf() and scanf() functions except of course they work on files. The general form of fprintf is
where fp is a file pointer associated with a file that has been opened for writing. The control string contains output specifications for the items in the lisr. The list may include variables, constants and strings Ex.
Here name is an array variable to type char and age is an integer variable. The general form of fscanf() is
Like scanf, fscanf also returns the numbers of items that are successfully read. When the end of file is reached, ite returns the value of EOF.
printf("Name,number,quantity and price:- ");
fseek(), ftell() and rewind() Functions:
Once a file has been opened, we may want to access the specific part of the file. This is done by positioning the file pointer at the desired position in the file. This can be achieved through the functions rewind() and fseek().
rewind():- rewind() positions the file pointer right at the begining of the file. The general statement is
fseek():- fseek() function is versatile since it can place the file pointer virtually anywhere in the file. Its general format is fseek(file pointer,+/-no of bytes,anchor);
On calling fseek it positions the file pointer ahead(if+) or behind(if-) the location specified by anchor. The anchor can be
1) seek_set - Begining of the file.
2) seek_end - End of file.
3) seek-cur - Current Position.
ftell():- ftell() is the function which gives you the current position of the file pointer in the file.
will return the current position of the file pointer in terms of byte which will be stored in integer.
Binary Data Files:
Some applications involve the use of data files to store blocks of data. Each block will generally represent complex data structure. For ex. a data file may contain multiple structures having the same composition or it may contain multile arrays of the same type and size. For such applications, it is desirable to read the entire block from the data file rather than reading or writing individual component within each block separately. The library functions fread() and fwrite() are used in such a situation. Each of these functions require four arguments pointer to the data block, the size of the data block, the number of data blocks being transferred the string pointer variable p.
For Ex. fwrite(&rec,sixeof(struct record),5,fp);
Using the array of structure you can input the 5 records from the terminal using for loop below.
struct record rec;
Then open the file to which you want to transfer the records using the fopen function.
Now all the inputed records will be transferred to file DATA by following statements
In the same way you can use fread() function also to read the records from a file.
Prev || Home || Next