FILE IO in ‘C’ by Dr P.Padmanabham Professor (CSE)&Director Bharat Institute of Engineering &Technology Hyderabad Mobile
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
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
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.
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);
Text-file Modes r - 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 (app end if file exists ) Note:- add b to above for binary files
Example of Opening & Closing a File The following segment of code illustrates opening and closing a file FILE *fp; If((fp=fopen(“test.txt", "r"))==NULL) { printf(“File:could not be opend\n”); exit(1); } fclose(fp);
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 tim e
Write to text file from key board #include 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*/ }
Count words and lines in a text file #include 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");
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); }
Using formated I/o on text files int 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 fscanf fprintf(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);
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.
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
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.
Binary file IO #include void main(int argc,char*argv[]){ FILE *fp; int i,n; struct { char name[30]; int empno; float sal; } emp;
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);
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);
printf("Empno:%5d\n",emp.empno); printf("Salary:%8.2f\n",emp.sal); } fclose(fp); }
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.
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)
Example of random access #include 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+");
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;}
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); }
Error Handling Functions The clearerr function void clearerr(FILE *stream); The clearerr function clears the end-of-file and error indicators for the stream pointed to by stream The feof function int 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.
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.