fread fwrite 的使用

下面是一个用fread,fwrite向结构体中写入结构体,读出结构体的代码:

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

struct stu
{
 char name[20];
 char sex[20];
 int age;
};

int save()
{
 struct stu mystu[3];
 FILE *fp;
 extern int errno;
 char fpath[]="record";
 int i;
// memset(mystu,0,sizeof(mystu));
 strcpy(mystu[0].name,"yang你的");
 printf("%s\n",mystu[0].name);
 strcpy(mystu[0].sex,"yang方法");
 mystu[0].age=23;
 strcpy(mystu[1].name,"cai方法");
  strcpy(mystu[1].sex,"cai读的");
 mystu[1].age=21;
 strcpy(mystu[2].name,"liu的");
 strcpy(mystu[2].sex,"liu");
 mystu[2].age=20;
 
 fp=fopen(fpath,"w");
 if(fp==NULL)
 {
  printf("can't open the file !");
  printf("errno:%d",errno);
  printf("ERROR :%s",strerror(errno));
  return 0;
 }
 else
 {
   printf("The file is opened");
 }
 i=fwrite(mystu,sizeof(mystu),1,fp);
 printf("%d bit was written.\n",i);
 fclose(fp);
 return 0;
}

int load()
{
 struct stu mystu[3];
 FILE *fp;
 extern int errno;
 char fpath[]="record";
 int i;
 
 fp=fopen(fpath,"rb");
 if(fp==NULL)
 {
  printf("can't open the file !");
  printf("errno:%d",errno);
  printf("ERROR :%s",strerror(errno));
  return 0;
 }
 else
 {
   printf("The file is opened");
 }
 i=fread(mystu,sizeof(mystu),1,fp);
 printf("%d bit was read.\n",i);
 
 int j;
 for(j=0;j<3;j++)
 {
    printf("%s %s %d\n",mystu[j].name,mystu[j].sex,mystu[j].age);
 }
 fclose(fp);
 return 0;
}

int main()
{
//    save();
load();
    return 0;

}
 
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值