Page 1 :
Unit 4. File Handling, Prof. Sachin Lamkane, Introduction:, Until now we have using the scanf() & printf() functions to read & write data. This works fine as long as the data is small. But when we deal with large amount of data then there are two problems., 1.It becomes complicated & time consuming to handle large volume of data through terminals. (Keyboard & screen)., 2. The entire data is lost when either the program is terminated or computer is turned off., The concept of file is used to store data on the disk & read whenever necessary, without destroying the data., C supports following operations performed on file., Naming a file, Opening a file, Reading data from file, Writing data to a file, Closing a file., Defining & Opening a File:, If we want to store data in a file, data structure of file is defined as FILE in the library of standard I/O(input/ output) function definitions., When we open a file, we must specify what we want to do with the file. For example, we may write data to the file or read the already existing data., Following is the general format for declaring & opening a file, FILE *fp; /*defining file pointer of type file*/, fp = fopen(“filename”, “mode”);, The first statement declares the variable fp as a “Pointer to the data type FILE”., The second statement opens the file named filename & assigns an identifier to the FILE type pointer fp. The second parameter mode indicates the purpose of opening this file. file opening mode is one of the following., r - open the file for reading only., w - open the file for writing only., a - open the file for appending mode., When we trying to open a file, one of the following things may happen., When the mode is ‘writing’, a file with the specified name is created if the file does not exist. The contents are deleted, if the file already exist, When the purpose is ‘appending’, the file is opened with the current contents safe. A file with the specified name is created if the file does not exist., If the purpose is ‘reading’, & if it exists, then the file is openedwith the current contents safe. Otherwise an error occurs., Consider the following statements:, FILE *fp1, *fp2;, fp1=fopen(“data”, “r”);, fp2=fopen(“result”, “w”);, The file data is opened for reading & result is opened in writing mode., Closing A File:, A file must be closed as soon as all operations on it have been completed. The general syntax of closing file is,, fclose( filepointer );, This would close the file associated with the file pointer filepointer., Consider the following segment of program., --------------------------, --------------------------, FILE *fp1, *fp2;, fp1=fopen(“Input”, “w”);, fp2=fopen(“Output”, “r”);, --------------------------, --------------------------, fclose(fp1); /* closing file input */, fclose(fp2); /*closing file output */, This program opens two files & closes them after all operations on them are completed., Following are the list of table shows important file handling functions., Input/Output operations on file:, getc() &putc() functions:, getc & putc functions are used to read & write a character from/ to a file respectively. Consider that a file is opened in write mode & file pointer is fp then the statement., putc (ch, fp);, writes the character contained in the character variable ch to the file associated with FILE pointer fp. Similarly, getc is used to read a character from a file that has been opened in read mode. For eg. The statement, c = getc(fp);, would read a character from the file whose file pointer is fp., The file pointer moves by one character position for every operation of getc or putc. The getc will stop reading when EOF(End-Of-File) is encountered., Example: Write a program to read data from the keyboard, write it to a file called Input, again read the same & display it on the screen., #include<stdio.h>, #include<conio.h>, void main(), {, FILE *fp;, charch;, printf(“Data Input ”);, fp=fopen(“Input”, “w”); /* Open input file in write mode */, while((ch=getchar())!=EOF), {, Putc(ch, fp);, }, fclose(fp); /* Close input file */, printf(“\n Data Output ”);, fp=fopen(“ Input ”, “r”);, while((ch=getc(fp))!=EOF), printf(“%c”, ch);, fclose(fp);, }, Output:, Data Input, Phaltan Education Society’s, Mudhoji College, Phaltan^2, Data Output, Phaltan Education Society’s, Mudhoji College Phaltan:, fgetc() & fputc() are the functions having same syntax as getc() and putc() functions. & also used on file as same way getc() & putc() are used., getw & putw functions:, The getw & putw are integer oriented functions that are used to read & write integer values. The general forms of getw & putw are,, putw(integer, fp);, getw(fp);, Example: A file named DATA contains a series of integer numbers. Write a code to read these numbers & then write all odd numbers to file ODD & all even numbers to file EVEN., #include<stdio.h>, #include<conio.h>, Void main(), {, FILE *f1, *f2, *f3;, int no, i;, printf(“Contents of DATA file”);, f1=fopen(“DATA”, “w”);, for(i=0;i<25;i++), {, scanff(“%d”, &no);, if(no==-1), break;, putw(no, f1);, }, fclose(f1);, f1=fopen(“DATA”, “r”);, f2=fopen(“ODD”, “w”);, f3=fopen(“EVEN”, “w”);, while(no=getw(f1)!=EOF), {, if(no%2==0), putw(no, f3); /* Write to EVEN file */, else, putw(no, f2); /* Write to ODD file */, }, fclose(f1);, fclose(f2);, fclose(f3);, f2=fopen(“ODD”, “r”);, f3=fopen(“EVEN”, “r”);, printf(“\n Contents of ODD file \n”);, while((no=getw(f2))!EOF), printf(“%d”,no);, printf(“\n Contents of EVEN file \n”);, while((no=getw(f3))!=EOF), printf(“%d”, no);, fclose(f2);, fclose(f3);, }, Output:, Contents of DATA file, 10 15 25 70 88 111 135 170 200 -1, Contents of ODD file, 15 25 111 135, Contents of EVEN file, 10 70 88 172 200, fprintf & fscanf functions:, fprintf & fscanf are file handling functions, that handles set of data values simultaneously. The functions fprintf & fscanf perform I/O operations that are identical to printf & scanf functions except they works on file., The general form of fprintf is,, fprintf(fp, “control string”, list);, Where, fp is a file pointer associated with a file that has been opened for writing mode. The control string contains output specifications for the items in the list. The list may include variables, constants & strings., For example,, fprintf(fp, “%s %d %f”, name, age, 50.55);, here, name is an array variable of type char, age is an int variable, 50.55 is float constant, The general form of fscanf is,, fscanf(fp, “control string”, list);, This statement reads items in the list from the file specified by fp, according to the specification, contained in the control string., For example,, fscanf(fp, “%s %d”, item, &quantity);, like scanf, fscanf also returns the number of items that are successfully read. When the end of file is reached, it returns the value EOF., Example:Write a program to open a file named inventory & store in it the following data. & display the same., Item No. Name Price Quantity, Soap 20.00 15, Oil 70.00 05, Sugar 30.00 10, Program:, #include<stdio.h>, #include<conio.h>, void main(), {, FILE *f1;, Int itemno, qty, i;, float price, value;, char item[10];, f1=fopen(“Inventory””, “w”);, printf(“\n Input Inventory Data: ”);, printf(“\n Item No. Name Price Quantity”);, for(i=0; i<3; i++), {, fscanf(stdin, “%d %s %f %d”, &itemno, &item, &price, &qty);, }, fclose(f1);, f1=fopen (“Inventory”, “r”);, printf(“\n Item No. Name Price Quantity Total”);, for(i=0;i<3;i++), {, fscanf(f1, “%d %s %f %d”, &itemno, &item, &price, &qty);, value=price*qty;, fprintf(stdout, “%d %s %f %d %f”, &itemno, &item, &price, &qty,, &value);, }, fclose(f1);, }, Output:, Input Inventory Data, Item No. Name Price Quantity, 1. Soap 20.00 10, 2. Oil 70.00 05, 3. Sugar 30.00 10, Item No. Name Price Quantity Total, 1. Soap 20.00 10 200.00, 2. Oil 70.00 05 350.00, 3. Sugar 30.00 10 300.00, Random Access To File:, C supports fseek(), ftell() and rewind() functions to accessing only a part of a file rather accessing file sequentially., ftell() :, ftell() function is useful in saving the current position of a file. It takes the following form., n= ftell (fp);, n would give the relative offset (in bytes) of the current position. This means that n bytes have been already read(or write)., rewind() :, Rewind takes a file pointer & resets the position to the start of the file. the syntax for using rewind function is,, rewind(fp);, If we use ftell() after rewind function the it would assign o to n because the file position is set to the start of the file by rewind., fseek() :, fseek() function is used to move the file position to a desired location within the file. It takes the following form., fseek(fileptr, offset, position);, where, fileptr is a pointer to the file concerned., offset is a number or variable of type long., position is an integer number., The offset specifies the number of position (bytes) to be moved from the location specified by position. The position can take one of the following three values., The offset may be positive, meaning move forward, or negative, meaning move backward., Consider example the operations of the fseek function., When the operation is successful, fseek returns a zero. If we attempt to move the file pointer beyond the file boundaries, an error occurs &fseek returns -1.