C语言:用二进制方式向文件读写一组数据(fread、fwrite)

  1. #include<stdio.h>
  2. #define SIZE 10
  3. struct student
  4. {
  5.   char name[10];
  6.   int num;
  7.   int age;
  8.   char addr[15];
  9. }stu[SIZE];
  10. //保存数据(fwrite)
  11. void save()
  12. {
  13.   FILE *fp;
  14.   fp = fopen("stu.dat","wb");
  15.   if(fp==NULL)
  16.   {
  17.       printf("file can not open!\n");
  18.       return;
  19.   }
  20.   for(int i=0;i<SIZE;i++)
  21.   {
  22.       if(fwrite(&stu[i],sizeof(struct student),1,fp)!=1)
  23.       {
  24.         printf("file write error!\n");
  25.       }
  26.   }
  27.   fclose(fp);
  28. }
  29. //读取数据(fread)
  30. void load()
  31. {
  32.   FILE *fp;
  33.   fp = fopen("stu.dat","rb");
  34.   if(fp==NULL)
  35.   {
  36.       printf("file can not open!\n");
  37.       return;
  38.   }
  39.   for(int i=0;i<SIZE;i++)
  40.   {   
  41.      if(fread(&stu[i],sizeof(struct student),1,fp)!=1)
  42.      {
  43.         if(feof(fp))
  44. {
  45.   fclose(fp);
  46.   return;
  47. }
  48. printf("file read error!\n");
  49.      }
  50.      printf("%-10s %4d %4d %-15s\n",stu[i].name,stu[i].num,stu[i].age,stu[i].addr);
  51.   }
  52.   fclose(fp);
  53. }
  54. int main()
  55. {
  56.    printf("Please enter data of students:\n");
  57.    for(int i=0;i<SIZE;i++)
  58.    {
  59.        scanf("%s%d%d%s",stu[i].name,&stu[i].num,&stu[i].age,stu[i].addr);
  60.    }
  61.    save();
  62.    load();
  63.    return 0;
  64. }
  65.  
posted @ 2015-08-06 22:05  XYQ全哥  阅读(7890)  评论(0编辑  收藏  举报