100 likes | 255 Views
Today’s Agenda. File Handling in C f open f close getc p utc f scanf f printf f tell fseek. getc() and putc(). getc() : gets a character from the file pointed by file pointer fp ch = getc( fp ) ; Putc(): puts the character to the file pointed by file pointer fp putc(ch,fp);.
E N D
Today’s Agenda • File Handling in C • fopen • fclose • getc • putc • fscanf • fprintf • ftell • fseek
getc() and putc() • getc() : gets a character from the file pointed by file pointer fp • ch = getc( fp ) ; • Putc(): puts the character to the file pointed by file pointer fp • putc(ch,fp);
Program to mimic copy command using getc and putc functions [Mayuri@localhost files]$ gcc -o cp file1.c […]$ ./cp /home/Mayuri/OS_Programs/permission.c per.c void main(int argc,char *argv[]) { FILE *fp1, *fp; int len=0 ; char ch; fp = fopen( argv[1], "r" ); if(fp == NULL) { printf("Invalid File\n"); exit(1); } fp1 = fopen( argv[2], "w" ); ch = getc( fp ) ; while ( ch != EOF ) { //value of EOF = -1 putchar( ch ); len++; putc(ch,fp1); ch = getc ( fp ); } printf("length of file = %d\n",len); fclose(fp); fclose( fp1 ); }
Program to show fscanf and fprintf int main(int argc,char *argv[]) { FILE *f1,*f2; int a[10]= {10,20,30,40,50,60,70,80,90,100}; int i,x; f1 = fopen(argv[1],"w"); if(f1 == NULL){ printf("File opening error!......\n"); exit(0); } for(i=0;i<10;i++) fprintf(f1,"%d ",a[i]); fclose(f1); f1 = fopen(argv[1],"a"); f2 = fopen(argv[2],"r"); while(!feof(f2)) { fscanf(f2,"%d ",&x); fprintf(f1,"%d ",x); } fclose(f1); fclose(f2); } Content of file2.txt is 200 300 400 500 600 700 800 900 1000 [Mayuri@localhost files]$ ./a.out file1.txt file2.txt output : see content of file1.txt 10 20 30 40 50 60 70 80 90 100 200 300 400 500 600 700 800 900 1000
Random Access to Files • File functions to achieve this • Ftell() • Fseek() • Rewind()
ftell() • Syntax • FILE *fp; • n = ftell(fp); • Where n is a long integer • It gives the number of bytes already read or written till the current position.
Rewind() • Syntax • FILE *fp; • rewind(fp) • File pointer is set to start of the file. rewind(fp); n = ftell(fp); Value of n = 0;
fseek() • Syntax • FILE *fp; • fseek(fp,offset,position); • fp – file pointer • position – it’s a integer number (0,1, or 2) • 0 – specifies beginning of file • 1 - specifies current position • 2 – specifies end of file • offset – it is the number of bytes to be moved from the location specified by position.
Operations of fseek() • Fseek(fp,0L,0) – go to the beginning (like rewind) • Fseek(fp,0L,1) – stay at the current position. • Fseek(fp,0L,2) – go the end of the file. • Fseek(fp,m,0) – move to (m+1)th byte in the file from start • Fseek(fp,m,1) – move m bytes forwards from current position • Fseek(fp,-m,1)- move m bytes backwards from current position • Fseek(fp,-m,2)-move m bytes backwards from the end of the file