zoukankan      html  css  js  c++  java
  • 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! ");
    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! ");
    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! ");
    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! ");
    49.      }
    50.      printf("%-10s %4d %4d %-15s ",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: ");
    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.  
  • 相关阅读:
    并发运行的思维模型
    进程和线程的区别
    拿来主义
    同步组件合作和团队合作 让世界变得更美好
    strace a++;b++;a+b;
    System 88: GDB Overview
    numpy多维数组维度及添加轴的理解
    Numpy入门
    python列表list 和numpy.array区别
    数组的生成方法
  • 原文地址:https://www.cnblogs.com/XYQ-208910/p/4709350.html
Copyright © 2011-2022 走看看