You are on page 1of 39

FILE HANDLING

Real life situations involve large volume of data and in such cases, the console oriented I/O operations pose two major problems : 1) It becomes cumbersome and time consuming to handle large volumes of data through terminals.
2) The entire data is lost when either the program is terminated or computer is turned off therefore it is necessary to have more flexible approach where data can be stored on the disks and read whenever necessary, without destroying the data. This method employs the concept of files to store data.

File is a place where data can be stored on the disks and read whenever necessary, without destroying the data. File basic operation: a) Naming a file b) Opening a file c) Reading data from a file d) Writing data to a file e) Closing a file

File operation functions in C:


Function Name fopen() fclose getc() putc() fprintf() fscanf() getw() putw() fseek() ftell() rewind() Operation Creates a new file for use Opens a new existing file for use Closes a file which has been opened for use Reads a character from a file Writes a character to a file Writes a set of data values to a file Reads a set of data values from a file Reads a integer from a file Writes an integer to the file Sets the position to a desired point in the file Gives the current position in the file Sets the position to the beginning of the file

Defining and opening a file


If we want to store data in a file in the secondary memory, we must specify certain things about the file, to operating system. They are: a) Filename ( contains primary name and an optional period with the extension e.g student.c b) Data structure ( data structure of file is defined as FILE in the standard I/O library definition. All files should be declared as type FILE. FILE is a defined datatype) c) Purpose ( when we open a file , we must specify what we want to do with the file e.g read or write )

FILE *fp; fp=fopen(filename,mode); first line : The variable fp is a pointer to the data type FILE. second line: opens the file named file name and assigns an identifier to the FILE type pointer fp The file open function (fopen) serves two purposes: It makes the connection between the physical file and the stream. It creates a program file structure to store the information C needs to process the file.

FILE *p1, *p2; p1=fopen(data,r); p2=fopen(results,w); In case the results file already exists, its contents are deleted and the files are opened as a new file. If data file does not exist error will occur.

In C, each file is simply a sequential stream of bytes. C imposes no structure on a file.

A file must first be opened properly before it can be accessed for reading or writing. When a file is opened, a stream is associated with the file. Successfully opening a file returns a pointer to (i.e., the address of) a file structure, which contains a file descriptor and a file control block.
Once the files are open, they stay open until you close them or end the program (which will close all files.)

File Information Table


A program requires several pieces of information about a file, including the name the OS uses for it, the position of the current character, etc. C uses a structure called FILE (defined in stdio.h) to store the attributes of a file.

fopen

File Open Modes

R+ existing file is opened to the beginning for both reading and writing W+ same as w except both for reading and writing A+ same as a except for reading and writing

We can open and use number of files at a time .

More on File Open Modes

The statement: FILE *fptr1, *fptr2 ; declares that fptr1 and fptr2 are pointer variables of type FILE. They will be assigned the address of a file descriptor, that is, an area of memory that will be associated with an input or output stream. Whenever you are to read from or write to the file, you must first open the file and assign the address of its file descriptor (or structure) to the file pointer variable.

INPUT AND OUTPUT OPERATIONS ON FILES


Getc and putc ( for character) Getw and putw ( for integers) Fprintf and fscanf ( for both integer and character)

a) Getc and putc


Analogous to getchar and putchar functions Handles one character at a time. putc( c , fptr) writes the character contained in the character variable c to the file associated with FILE pointer fptr C=getc(fptr); would read a character from the file whose file pointer is fptr

Testing EOF(end-of-file) is important. Any attempt to read past the end of file might either cause the program to terminate with an error or result in an infinite loop situation.

b) Getw and putw


Are integer oriented functions. Similar to getc and putc and are used to read and write integer values. Putw(integer,fp); Getw(fp);

c) Fprintf and fscanf functions


Putc, getc, putw, getw can handle only one character at a time Fprintf and fscanf allow to handle a group of mixed data simultaneously. Similar to scanf and printf except they work on files.

fprintf

fprintf( fp , control string , list);

3 parameters :
fp - file pointer associated with a file that has been opened for writing Control string - contains output specification for the items in the list List may include variables , constants , strings

Fprintf ( fptr , %s %d %f , name , age , 7.5 ); Here, name is an array variable of type char and age is an int variable

e.g:

int a = 5, b = 20 ; FILE *fptr2 ; fptr2 = fopen ( "results", "w" ) ; fprintf ( fptr2, "%d %d\n", a, b ) ;

the fprintf functions would write the values stored in a and b to the file "pointed" to by fptr2.

Fscanf Fscanf(fptr , %s %d, item , &quantity); Fscanf also returns the number of items that are successfully read. When the end of file is reached, it returns the value of EOF.

ERROR HANDLING
It is possible that an error may occur during I/O operations on a file. Typical error situation occur: a) Trying to read beyond the end-of-file mark b) Device overflow c) Trying to use a file that has not been opened d) Trying to perform an operation on a file, when the file is opened for another type of operation e) Opening a file with an invalid filename f) Attempting to write to a write-protected file

If we fail to check such read and write errors, a program may behave abnormally when an error occurs. We have two status inquiry library function that help us detect I/O errors in the files: a) feof b) ferror

a) Feof used to test for an EOF condition. it takes a FILE pointer as its only argument and returns a nonzero integer value of all of the data from the specified file has been read and returns zero otherwise E.g if( feof(fptr)) printf( end of data\n); Would display the message end of dat on reaching the end of file condition

b) Ferror reports the status of the file indicated. It also takes a FILE pointer as its argument and returns a nonzero integer if an error has been detected up to that point, during processing . It returns zero otherwise. If(ferror(fptr ) != 0) printf(an error has occurred \n); Would print the error message , if the reading is not successful.

Whenever a file is opened using fopen function , a file pointer is returned. If the file cannot be opened for some reason, then the function returns a NULL pointer. This facility can also be used to test whether a file has been opened or not. If(fp==NULL) printf(file could not be opened \n); e.g: FILE *fptr ; fptr = fopen ( "mydata", "r") ; if (fptr == NULL) { printf ("File 'mydata' did not open.\n") ; }

Reading and Writing Files


#include <stdio.h> int main ( ) { FILE *outfile, *infile ; int b = 5, f ; float a = 13.72, c = 6.68, e, g ; outfile = fopen ("testdata", "w") ; fprintf (outfile, "%6.2f%2d%5.2f", a, b, c) ; fclose (outfile) ;

Reading and Writing Files


infile = fopen ("testdata", "r") ; fscanf (infile,"%f %d %f", &e, &f, &g) ; printf ("%6.2f%2d%5.2f\n", a, b, c) ; printf ("%6.2f,%2d,%5.2f\n", e, f, g) ; } 12345678901234567890 **************************** 13.72 5 6.68 13.72, 5, 6.68

Closing a file
The input output library supports the function to close a file; it is in the following format. fclose(file_pointer); A file must be closed as soon as all operations on it have been completed. This would close the file associated with the file pointer. Observe the following program. . FILE *p1 *p2; p1=fopen (Input,w); p2=fopen (Output,r); . fclose(p1); fclose(p2) ;

Closing a file will release the file descriptor space and I/O buffer memory.

Example
#include< stdio.h > main() { file *f1; printf(Data input output); f1=fopen(Input,w); while((c=getchar())!=EOF) putc(c,f1); fclose(f1); printf(nData outputn); f1=fopen(INPUT,r); while((c=getc(f1))!=EOF) printf(%c,c); fclose(f1); }

/*Open the file Input*/ /*get a character from key board*/ /*write a character to input*/ /*close the file input*/ /*Reopen the file input*/
Check for feof and ferror functions End_of_File

Reading & writing The getw and putw functions


/*Example program for using getw and putw functions*/ #include< stdio.h > while((number=getw(f1))!=EOF)/* Read from data main() file*/ { { if(number%2==0) FILE *f1,*f2,*f3; putw(number,f3);/*Write to even file*/ int number I; printf(Contents of the data filenn); else putw(number,f2);/*write to odd file*/ f1=fopen(DATA,W); for(I=1;I< 30;I++) } { fclose(f1); fclose(f2); fclose(f3); scanf(%d,&number); f2=fopen(ODD,r); f3=fopen(EVEN,r); if(number==-1) printf(nnContents of the odd filenn); break; while(number=getw(f2))!=EOF) putw(number,f1); printf(%d%d,number); } printf(nnContents of the even file); fclose(f1); while(number=getw(f3))!=EOF) f1=fopen(DATA,r); printf(%d,number); f2=fopen(ODD,w); f3=fopen(EVEN,w); fclose(f2); fclose(f3);
}

/*Program to handle mixed data types*/


#include< stdio.h > main() fclose (fp); { fprintf(stdout,nn); FILE *fp; fp=fopen(filename,r); int num,qty,I; printf(Item name number float price,value; price quantity value); char item[10],filename[10]; for(I=1;I< =3;I++) printf(Input filename); { scanf(%s,filename); fscanf(fp,%s%d%f%d,item,&n fp=fopen(filename,w); umber,&prince,&quality); printf(Input inventory datann0; value=price*quantity); printf(Item namem number price quantityn); fprintf(stdout,%s%d%f%d%dn for I=1;I< =3;I++) ,item,number,price,quantity,va { lue); fscanf(stdin,%s%d%f%d,item,&number,&price,&quality); } fprintf(fp,%s%d%f%d,itemnumber,price,quality); fclose(fp); } }

Random access to files


So far we have studied file functions that are useful for reading and writing data sequentially. Sometimes it is required to access only a particular part and not the complete file. Random access to a file can be done by using the following function: fseek() , ftell() , rewind() available in the I/O library

a) Ftell :
Takes a file pointer and return a number of type long, that corresponds to the current position. This function is useful in saving the current position of a file, which can be used later in the program.

n = ftell(fptr);
n would give the relative offset(in bytes) of the current position. This means n bytes have already been read ( or written)

b) Rewind(): Takes a file pointer and resets the position to the start of the file. rewind(fptr); N= ftell(fptr);

Would assign 0 to n because the file position has been set to the start of the file by rewind(). First byte in file is numbered as 0 then 1 and so on.. Rewind() function helps us in reading file more than once, without having to close and open the file. Whenever a file is opened for reading and writing rewind is done implicitly.

Fseek(): Used to move the file position to a desired location within the file fseek(file pointer,offset, position); File pointer : - pointer to the file concerned. Offset:- number or variable of type long Offset specifies the number of positions (bytes) to be moved from the location specified by the position. Offset may be positive ,meaning moving forward or negative , moving backwards position:- an integer number. The position can take the 3 values. 0 Beginning of the file 1 Current position 2 End of file.

When the operation is successful, fseek returns a zero. If we attempt to move the file pointer beyond boundaries, an error occurs and fseek returns -1 (minus one)

STATEMENT Fseek(fp,0L,0) Fseek(fp,0L,1) Fseek(fp,0L,2) Fseek(fp,m,0)

MEANING Go to the beginning (similar to the rewind) Stay at the current position ( rarely used) Go to the EOF , past the last character of the file Move to (m+1)th byte in the file

Fseek(fp,m,1) Fseek(fp,-m,1)
Fseek(fp,-m,2)

Go forward by m bytes Go backward by m bytes from the current position


Go backward by m bytes from the end ( positions the file to the mth character from the end )

What is the meaning of a) Fseek(fp , -1L ,2) b) Fseek(fp,-2L,1)

You might also like