1 / 8

Today’s Agenda

Today’s Agenda. File Operations. FILE *fp File pointer fp = fopen(“filename”,”mode”) Opens the file fclose(fp) Closes the file. c= getc(fp); Reads a character from a file putc(c,fp); Writes a charater to a file int n = getw(fp); Reads an integer from a file putw(n,fp);

Download Presentation

Today’s Agenda

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Today’s Agenda File Operations

  2. FILE *fp • File pointer • fp = fopen(“filename”,”mode”) • Opens the file • fclose(fp) • Closes the file

  3. c= getc(fp); • Reads a character from a file • putc(c,fp); • Writes a charater to a file • int n = getw(fp); • Reads an integer from a file • putw(n,fp); • Writes the integer to a file

  4. int main() { FILE *f1; char c; f1 = fopen("input.txt","w"); while((c=getchar()) != EOF) { putc(c,f1); } fclose(f1); f1 = fopen("input.txt","r"); while((c=getc(f1)) != EOF) printf("%c ",c); fclose(f1); }

  5. fscanf() & fprintf()

  6. int main() { struct student { int idno; char name[10]; float marks; }s[10]; int i=0; FILE *fin,*fout; fin = fopen("input.txt","r"); if(fin == NULL) { printf("Can not open file!...\n"); exit(0); } fout = fopen("output.txt","w"); if(fout == NULL) { printf("Can not open file!...\n"); exit(0); } while(!feof(fin)) { fscanf(fin,"%d %s %f",&s[i].idno,s[i].name,&s[i].marks); fprintf(fout,"%d %s %f",s[i].idno,s[i].name,s[i].marks); i++; } fclose(fin); fclose(fout); for(j=0;j<i;j++) printf("%d %s %f\n",s[j].idno,s[j].name,s[j].marks); }

  7. Command line arguments

  8. int main(int argc,char *argv[]) { struct student { int idno; char name[10]; float marks; }s[10]; int i=0; FILE *fin,*fout; fin = fopen(argv[1],"r"); if(fin == NULL) { printf("Can not open file!...\n"); exit(0); } fout = fopen(argv[2],"w"); if(fout == NULL) { printf("Can not open file!...\n"); exit(0); } while(!feof(fin)) { fscanf(fin,"%d %s %f",&s[i].idno,s[i].name,&s[i].marks); printf("%d %s %f\n",s[i].idno,s[i].name,s[i].marks); fprintf(fout,"%d %s %f",s[i].idno,s[i].name,s[i].marks); } fclose(fin); fclose(fout); }

More Related