File Handling

39
FILE HANDLING

Transcript of File Handling

Page 1: File Handling

FILE HANDLING

Page 2: 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.

Page 3: File Handling

• 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 fileb) Opening a filec) Reading data from a filed) Writing data to a filee) Closing a file

Page 4: File Handling

File operation functions in C: Function Name Operationfopen() Creates a new file for use

Opens a new existing file for use

fclose Closes a file which has been opened for usegetc() Reads a character from a fileputc() Writes a character to a filefprintf() Writes a set of data values to a filefscanf() Reads a set of data values from a filegetw() Reads a integer from a fileputw() Writes an integer to the filefseek() Sets the position to a desired point in the fileftell() Gives the current position in the filerewind() Sets the position to the beginning of the file

Page 5: File Handling

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 )

Page 6: File Handling

• 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.

Page 7: File Handling

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.

Page 8: File Handling

• 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.)

Page 9: File Handling

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.

Page 10: File Handling

fopen

Page 11: File Handling

File Open Modes

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

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

Page 12: File Handling

More on File Open Modes

Page 13: File Handling

• 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.

Page 14: File Handling

INPUT AND OUTPUT OPERATIONS ON FILES

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

character)

Page 15: File Handling

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

Page 16: File Handling

• 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.

Page 17: File Handling

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);

Page 18: File Handling

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.

Page 19: File Handling

fprintf• fprintf( fp , “control string” , list); 3 parameters : fp - file pointer associated with a file that has been opened for

writingControl string - contains output specification for the items in the listList – 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

Page 20: File Handling

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.

Page 21: File Handling

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.

Page 22: File Handling

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 markb) Device overflowc) Trying to use a file that has not been openedd) Trying to perform an operation on a file, when the

file is opened for another type of operatione) Opening a file with an invalid filenamef) Attempting to write to a write-protected file

Page 23: File Handling

• 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

Page 24: File Handling

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

Page 25: File Handling

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.

Page 26: File Handling

• 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") ; }

Page 27: File Handling

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) ;

Page 28: File Handling

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

Page 29: File Handling

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.

Page 30: File Handling

Example

#include< stdio.h > main() { file *f1; printf(“Data input output”); f1=fopen(“Input”,”w”); /*Open the file Input*/ while((c=getchar())!=EOF) /*get a character from key board*/ putc(c,f1); /*write a character to input*/ fclose(f1); /*close the file input*/ printf(“nData outputn”); f1=fopen(“INPUT”,”r”); /*Reopen the file input*/ while((c=getc(f1))!=EOF) printf(“%c”,c); fclose(f1); } End_of_File

Check for feof and ferror functions

Page 31: File Handling

Reading & writing The getw and putw functions

/*Example program for using getw and putw functions*/ #include< stdio.h > main() { FILE *f1,*f2,*f3; int number I; printf(“Contents of the data filenn”); f1=fopen(“DATA”,”W”); for(I=1;I< 30;I++) { scanf(“%d”,&number); if(number==-1) break; putw(number,f1); } fclose(f1); f1=fopen(“DATA”,”r”); f2=fopen(“ODD”,”w”); f3=fopen(“EVEN”,”w”);

while((number=getw(f1))!=EOF)/* Read from data file*/ { if(number%2==0)

putw(number,f3);/*Write to even file*/ else

putw(number,f2);/*write to odd file*/ }

fclose(f1); fclose(f2); fclose(f3); f2=fopen(“ODD”,”r”); f3=fopen(“EVEN”,”r”); printf(“nnContents of the odd filenn”); while(number=getw(f2))!=EOF) printf(“%d%d”,number); printf(“nnContents of the even file”); while(number=getw(f3))!=EOF) printf(“%d”,number); fclose(f2); fclose(f3); }

Page 32: File Handling

/*Program to handle mixed data types*/

#include< stdio.h > main() { FILE *fp; int num,qty,I; float price,value; char item[10],filename[10]; printf(“Input filename”); scanf(“%s”,filename); fp=fopen(filename,”w”); printf(“Input inventory datann”0; printf(“Item namem number price quantityn”); for I=1;I< =3;I++) { fscanf(stdin,”%s%d%f%d”,item,&number,&price,&quality); fprintf(fp,”%s%d%f%d”,itemnumber,price,quality); }

fclose (fp); fprintf(stdout,”nn”); fp=fopen(filename,”r”); printf(“Item name number price quantity value”); for(I=1;I< =3;I++) { fscanf(fp,”%s%d%f%d”,item,&number,&prince,&quality); value=price*quantity”); fprintf(“stdout,”%s%d%f%d%dn”,item,number,price,quantity,value); } fclose(fp); }

Page 33: File Handling

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

Page 34: File Handling

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)

Page 35: File Handling

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.

Page 36: File Handling

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 longOffset 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 backwardsposition:- an integer number.

• The position can take the 3 values. 0 Beginning of the file 1 Current position 2 End of file.

Page 37: File Handling

• 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)

Page 38: File Handling

STATEMENT MEANING

Fseek(fp,0L,0) Go to the beginning (similar to the rewind)

Fseek(fp,0L,1) Stay at the current position ( rarely used)

Fseek(fp,0L,2) Go to the EOF , past the last character of the file

Fseek(fp,m,0) Move to (m+1)th byte in the file

Fseek(fp,m,1) Go forward by m bytes

Fseek(fp,-m,1) Go backward by m bytes from the current position

Fseek(fp,-m,2) Go backward by m bytes from the end ( positions the file to the mth character from the end )

Page 39: File Handling

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