80 likes | 231 Views
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);
E N D
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); • Writes the integer to a file
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); }
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); }
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); }