0
点赞
收藏
分享

微信扫一扫

c语言将结构体数组内容以二进制形式写入文件并读取输出

#include <stdio.h>
#include <stdlib.h>

struct Student{
    char name[20];
    int  id;
    int  age;
  };

int main()
{
    struct Student stus[3]={{"zhuangsan",123,18},{"lisi",124,19},{"wangwu",125,20}};
    struct Student temp[3];
    int size=sizeof(struct Student);
    FILE *fp=fopen("student.dat","rb+");
    fopen("student.dat","wb");
    if(fp!=NULL)
    {
       int count= fwrite(stus,size,3,fp);
       if(count==3)
       {
           printf("数组temp中的内容为: \n");
       }
    }
    fclose(fp);
    fopen("student.dat","rb");
    if(fp!=NULL)
    {
        int i;
        for(i=0;i<3;i++)
        {
            int count=fread(&temp,size,1,fp);
            if(count==1)
            {
                printf("姓名: %s\t学号: %d\t年龄: %d\n",temp->name,temp->id,temp->age);
            }
        }
        fclose(fp);
    }
    return 0;
}

 

举报

相关推荐

0 条评论