files_ex2.c (703B)
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <string.h> 4 5 struct Student { 6 char name[50]; 7 float grade; 8 int id; 9 }; 10 11 int 12 main(int argc, char *argv[]) 13 { 14 FILE *fp; 15 struct Student *s; 16 17 if ((s = malloc(sizeof(struct Student))) == NULL) { 18 fputs("malloc failed\n", stderr); 19 return 1; 20 } 21 22 if ((fp = fopen("data", "r")) == NULL) { 23 fputs("fopen failed\n", stderr); 24 return 1; 25 } 26 27 while (fscanf(fp, "%d %s %f", &s->id, s->name, &s->grade) != EOF) 28 printf("%d %s %.2f\n", s->id, s->name, s->grade); 29 30 fclose(fp); 31 free(s); 32 33 return 0; 34 }