1 //读写结构体 2 #include <stdio.h> 3 typedef struct student 4 { 5 int num; 6 char name[30]; 7 char sex; 8 float math; 9 float english; 10 float chinese; 11 12 }Stu; 13 14 Stu s[5] = 15 { 16 1001,"wukong",'x',99,99,99, 17 1002,"songjiang",'x',99,22,11, 18 1003,"baoyu",'x',79,33,100, 19 1004,"liudehua",'y',100,100,88, 20 1005,"zhaosi",'z',33,34,12 21 }; 22 23 int main(void) 24 { 25 26 //往文件中写入结构体 27 FILE* pf = fopen("G:/qtcode/stu.data","w+"); 28 if(pf == NULL) 29 exit(-1); 30 #if 1 31 //写入方式1 32 int i; 33 for(i = 0;i<sizeof(s)/sizeof(*s);i++) 34 { 35 fwrite((void*)(&s[i]),sizeof(Stu),1,pf); 36 } 37 #endif 38 #if 0 39 //写入方式2 40 fwrite((void*)s,sizeof(s),1,pf); 41 42 #endif 43 #if 0 44 //写入方式3 45 fwrite((void*)s,sizeof(Stu),5,pf); 46 47 #endif 48 49 50 51 rewind(pf); 52 //从文件中读结构体 53 #if 0 54 //读出方式1 55 Stu buf; 56 while( fread((void*)&buf,sizeof(Stu),1,pf) ) 57 { 58 printf("num = %d ",buf.num); 59 printf("name = %s ",buf.name); 60 printf("sex = %c ",buf.sex); 61 printf("math = %.2f ",buf.math); 62 printf("english = %.2f ",buf.english); 63 printf("chinese = %.2f ",buf.chinese); 64 printf("-------------- "); 65 } 66 #endif 67 68 #if 0 69 //读出方式2 70 Stu buf[3]; 71 int j,n; 72 while((n = fread((void*)buf,sizeof(Stu),3,pf)) > 0) 73 { 74 for(j = 0;j < n;j++) 75 { 76 printf("num = %d ",buf[j].num); 77 printf("name = %s ",buf[j].name); 78 printf("sex = %c ",buf[j].sex); 79 printf("math = %.2f ",buf[j].math); 80 printf("english = %.2f ",buf[j].english); 81 printf("chinese = %.2f ",buf[j].chinese); 82 printf("-------------- "); 83 } 84 } 85 #endif 86 87 #if 0 88 //读出方式3 89 Stu buf[5]; 90 int j; 91 fread((void*)buf,sizeof(Stu),5,pf); 92 for(j = 0;j < 5;j++) 93 { 94 printf("num = %d ",buf[j].num); 95 printf("name = %s ",buf[j].name); 96 printf("sex = %c ",buf[j].sex); 97 printf("math = %.2f ",buf[j].math); 98 printf("english = %.2f ",buf[j].english); 99 printf("chinese = %.2f ",buf[j].chinese); 100 printf("-------------- "); 101 } 102 #endif 103 return 0; 104 }