26
FILE IO in ‘C’ by Dr P.Padmanabham Professor (CSE)&Director Bharat Institute of Engineering &Technology Hyderabad Mobile 9866245898 [email protected]

FILE IO in ‘C’ by Dr P.Padmanabham Professor (CSE)&Director Bharat Institute of Engineering &Technology Hyderabad Mobile 9866245898 [email protected]

Embed Size (px)

Citation preview

Page 1: FILE IO in ‘C’ by Dr P.Padmanabham Professor (CSE)&Director Bharat Institute of Engineering &Technology Hyderabad Mobile 9866245898 ppadmanabham@yahoo.com

FILE IO in ‘C’

byDr P.Padmanabham

Professor (CSE)&Director Bharat Institute

of Engineering &Technology Hyderabad

Mobile 9866245898 [email protected]

Page 2: FILE IO in ‘C’ by Dr P.Padmanabham Professor (CSE)&Director Bharat Institute of Engineering &Technology Hyderabad Mobile 9866245898 ppadmanabham@yahoo.com

Topics Coverd• Introduction to Files• Text files- character IO• Data Text files –Formatted IO • Variable Argument Functions• Handling Binary data files• Random access of files• Error handling in File IO• Some basic ideas of Low level IO

Page 3: FILE IO in ‘C’ by Dr P.Padmanabham Professor (CSE)&Director Bharat Institute of Engineering &Technology Hyderabad Mobile 9866245898 ppadmanabham@yahoo.com

Text and Binary Files

• A file is stream of bytes. A file is also referred as stream.

• Most people classify files in two categories: binary files and ASCII (text) files

• At heart all files are binary files -- that is, a collection of 1s and 0s.

• But there is a subset of binary files we call ASCII, or plain text files, where all the bytes stored are in ASCII

Page 4: FILE IO in ‘C’ by Dr P.Padmanabham Professor (CSE)&Director Bharat Institute of Engineering &Technology Hyderabad Mobile 9866245898 ppadmanabham@yahoo.com

Text and binary files contd.

• Since a text file holds printable characters (ASCII) it can be edited by a text editor .

• Examples of Text files- program source files and some data files.

• A binary file is one that holds information in bytes that may not be printable or editable.

• Examples of binary files-obj, exe files and some data files.

Page 5: FILE IO in ‘C’ by Dr P.Padmanabham Professor (CSE)&Director Bharat Institute of Engineering &Technology Hyderabad Mobile 9866245898 ppadmanabham@yahoo.com

File Pointer• FILE *fp; • FILE is a structure difined in stdio.h.• FILE *fopen(const char *filename, const char

*mode);• To open a file you need to use the fopen function,

which returns a FILE pointer on success and NULL on failure.

• Once you've opened a file successfully , you can use the FILE pointer to perform input and output functions on the file.

• To close a file you need to use int fclose(FILE *fp);

Page 6: FILE IO in ‘C’ by Dr P.Padmanabham Professor (CSE)&Director Bharat Institute of Engineering &Technology Hyderabad Mobile 9866245898 ppadmanabham@yahoo.com

Text-file Modesr - open for reading (file must exist)

w - open for writing (file overwritten if exists)

a - open for appending (file need not exist)

r+ - open for reading and writing, start at beginning

(file must exist)

w+ - open for reading and writing (overwrite file)

a+ - open for reading and writing (append if file

exists) Note:- add b to

above for binary files

Page 7: FILE IO in ‘C’ by Dr P.Padmanabham Professor (CSE)&Director Bharat Institute of Engineering &Technology Hyderabad Mobile 9866245898 ppadmanabham@yahoo.com

Example of Opening & Closing a File

The following segment of code illustrates opening and closing a fileFILE *fp; If((fp=fopen(“test.txt", "r"))==NULL) { printf(“File:could not be opend\n”); exit(1);}fclose(fp);

Page 8: FILE IO in ‘C’ by Dr P.Padmanabham Professor (CSE)&Director Bharat Institute of Engineering &Technology Hyderabad Mobile 9866245898 ppadmanabham@yahoo.com

Character I/O on text files

• int fgetc (FILE *fp);• Int fputc(int c,FILE *fp);• The fgetc function allows you to read

a character at a time• The fputc function allows you to

write a character at a time

Page 9: FILE IO in ‘C’ by Dr P.Padmanabham Professor (CSE)&Director Bharat Institute of Engineering &Technology Hyderabad Mobile 9866245898 ppadmanabham@yahoo.com

Write to text file from key board

#include<stdio.h> void main() { FILE *fp; char c; fp=fopen("my1.dat",“w"); while((c=fgetc(stdin))!=EOF)fputc(c,fp); fclose(fp);/* EOF is ctl z in DOS and ctl d in unix*/

}

Page 10: FILE IO in ‘C’ by Dr P.Padmanabham Professor (CSE)&Director Bharat Institute of Engineering &Technology Hyderabad Mobile 9866245898 ppadmanabham@yahoo.com

Count words and lines in a text file#include<stdio.h>#include<stdlib.h>void main(int argc,char *argv[]){ FILE *fp; int wc=0,lc=0; char c; if(argc!=2) {printf(“Error..File name required\n); exit(1);} fp=fopen(argv[1],"r");

Page 11: FILE IO in ‘C’ by Dr P.Padmanabham Professor (CSE)&Director Bharat Institute of Engineering &Technology Hyderabad Mobile 9866245898 ppadmanabham@yahoo.com

while((c=fgetc(fp))!=EOF) { if(c==' ')wc++; If(c=='\n') {

wc++; lc++;

while((c=fgetc(fp))==' '); } } printf("WC=%d\tLC=%d\n",wc,lc); fclose(fp);}

Page 12: FILE IO in ‘C’ by Dr P.Padmanabham Professor (CSE)&Director Bharat Institute of Engineering &Technology Hyderabad Mobile 9866245898 ppadmanabham@yahoo.com

Using formated I/o on text filesint fprintf(FILE *fp,char *fmt,…)int fscanf(FILE *fp,char *fmt,…) For example the following code writes one integer and one float into the file using fprintf and reads back using fscanffprintf(fp, “%d \t % f \n“, i, f);/* you have to position the file back to read what is written*/fscanf(fp, “%d % f “, &i, &f);

Page 13: FILE IO in ‘C’ by Dr P.Padmanabham Professor (CSE)&Director Bharat Institute of Engineering &Technology Hyderabad Mobile 9866245898 ppadmanabham@yahoo.com

Binary data files• Data can be stored either in text mode(previous

section) or in binary mode.• In text data files, data needs to be converted back

and forth from binary to ASCII while writing and reading where as in binary mode directly the memory image can be stored and retrieved.

• Another incidental advantage of binary data files as against text data files is that they cannot be edited by a text editor and therefore cannot be tampered easily.

• Binary files occupy less space. Imagine 1 million records stored in a database.

Page 14: FILE IO in ‘C’ by Dr P.Padmanabham Professor (CSE)&Director Bharat Institute of Engineering &Technology Hyderabad Mobile 9866245898 ppadmanabham@yahoo.com

Binary data file IO-fread()• int fread( void *buffer, size_t size, size_t num, FILE *stream );• The function fread() reads num number of

objects (where each object is size bytes) from the stream and places them into the memory pointed to by buffer.

• The return value of the function is the number of things(objects) read and 0 when eof is encountered

Page 15: FILE IO in ‘C’ by Dr P.Padmanabham Professor (CSE)&Director Bharat Institute of Engineering &Technology Hyderabad Mobile 9866245898 ppadmanabham@yahoo.com

Binary data file IO- fwrite()

• int fwrite( const void *buffer, size_t size, size_t count, FILE *stream );

• The fwrite() function writes, from the memory pointed by buffer, count number of objects of size size to stream.

• The return value is the number of objects written.

Page 16: FILE IO in ‘C’ by Dr P.Padmanabham Professor (CSE)&Director Bharat Institute of Engineering &Technology Hyderabad Mobile 9866245898 ppadmanabham@yahoo.com

Binary file IO#include<stdio.h>void main(int argc,char*argv[]){FILE *fp;int i,n;struct{ char name[30]; int empno; float sal;} emp;

Page 17: FILE IO in ‘C’ by Dr P.Padmanabham Professor (CSE)&Director Bharat Institute of Engineering &Technology Hyderabad Mobile 9866245898 ppadmanabham@yahoo.com

if(argc!=2){ printf("Error...file name not given\n"); exit(1);}fp=fopen(argv[1],"wb");for(i=0;i<3;i++){ fflush(stdin); printf("enter Name:"); gets(emp.name);

Page 18: FILE IO in ‘C’ by Dr P.Padmanabham Professor (CSE)&Director Bharat Institute of Engineering &Technology Hyderabad Mobile 9866245898 ppadmanabham@yahoo.com

printf("enter empno:"); scanf("%d",&emp.empno); printf("enter Sal:"); scanf("%f",&emp.sal); n=fwrite(&emp,sizeof(emp),1,fp); printf("%d \n",n);}fp=freopen(argv[1],"rb",fp); while((fread(&emp,sizeof(emp),1,fp))) { printf("Name:%s\n",emp.name);

Page 19: FILE IO in ‘C’ by Dr P.Padmanabham Professor (CSE)&Director Bharat Institute of Engineering &Technology Hyderabad Mobile 9866245898 ppadmanabham@yahoo.com

printf("Empno:%5d\n",emp.empno); printf("Salary:%8.2f\n",emp.sal); }fclose(fp);}

Page 20: FILE IO in ‘C’ by Dr P.Padmanabham Professor (CSE)&Director Bharat Institute of Engineering &Technology Hyderabad Mobile 9866245898 ppadmanabham@yahoo.com

Random access of file

• fseek() function sets the file position indicator for the stream pointed to by the FILE pointer to a position you seeks within a file and modify it.

• Its syntax is: fseek(FILE *stream, long int offset, int whence)

• The value of whence must be one of the constants SEEK_SET, SEEK_CUR, or SEEK_END, to indicate whether the offset is relative to the beginning of the file, the current file position, or the end of the file, respectively.

Page 21: FILE IO in ‘C’ by Dr P.Padmanabham Professor (CSE)&Director Bharat Institute of Engineering &Technology Hyderabad Mobile 9866245898 ppadmanabham@yahoo.com

fell() and rewind()• The ftell function obtains the current value of

the file position indicator for the stream pointed to by stream.

• Syntax long ftell(FILE *stream)• The rewind function sets the file position

indicator for the stream pointed to by stream to the beginning of the file. It is equivalent to:

• fseek(stream, 0L, SEEK_SET)• Sntax: void rewind(FILE* stream)

Page 22: FILE IO in ‘C’ by Dr P.Padmanabham Professor (CSE)&Director Bharat Institute of Engineering &Technology Hyderabad Mobile 9866245898 ppadmanabham@yahoo.com

Example of random access#include<stdio.h>void main(){FILE *fp;int i,n;struct{ char name[30]; int empno; float sal; } emp; long rpos,f_size; rpos=41L; fp=fopen("temp.dat","r+");

Page 23: FILE IO in ‘C’ by Dr P.Padmanabham Professor (CSE)&Director Bharat Institute of Engineering &Technology Hyderabad Mobile 9866245898 ppadmanabham@yahoo.com

fseek(fp,0,SEEK_END); if(fgetc(fp)==EOF){ f_size=ftell(fp); printf("File Size:%d\n",f_size); }while(1){ printf("which record?\n"); scanf("%d",&n); if(n<0)break; if(rpos*(n-1)>=f_size-1){printf("NO Record\n");continue;}if(fseek(fp,rpos*(n-1),SEEK_SET)){ printf("ERROR!!!\n");continue;}

Page 24: FILE IO in ‘C’ by Dr P.Padmanabham Professor (CSE)&Director Bharat Institute of Engineering &Technology Hyderabad Mobile 9866245898 ppadmanabham@yahoo.com

fscanf(fp,"%s %d %f", emp.name,&emp.empno,&emp.sal); printf("Name:%s\n",emp.name); printf("Empno:%5d\n",emp.empno); printf("Salary:%8.2f\n",emp.sal); emp.sal=25000; fseek(fp,rpos*(n-1),SEEK_SET); fprintf(fp1,"%25s\t%5d\t%10.2f\n",

emp.name,emp.empno,emp.sal); } fclose(fp);}

Page 25: FILE IO in ‘C’ by Dr P.Padmanabham Professor (CSE)&Director Bharat Institute of Engineering &Technology Hyderabad Mobile 9866245898 ppadmanabham@yahoo.com

Error Handling Functions• The clearerr functionvoid clearerr(FILE *stream); The clearerr function clears the end-of-file and

error indicators for the stream pointed to by stream

• The feof functionint feof(FILE *stream); The feof function tests the end-of-file indicator

for the stream pointed to by stream and returns nonzero if and only if the end-of-file indicator is set for stream, otherwise it returns zero.

Page 26: FILE IO in ‘C’ by Dr P.Padmanabham Professor (CSE)&Director Bharat Institute of Engineering &Technology Hyderabad Mobile 9866245898 ppadmanabham@yahoo.com

Error handling contd…• The ferror function int ferror(FILE *stream); The ferror function tests the error indicator for the

stream pointed to by stream and returns nonzero if and only if the error indicator is set for stream, otherwise it returns zero.

• The perrorr function void perror(const char *s); The perror function maps the error number in the

integer expression errno to an error message. It writes a sequence of characters to the standard error stream ,the string pointed to by s followed by a colon (:) and a space; then an appropriate error message string .