您的位置:首页 > 其它

fread fwrite 的使用

2012-05-01 22:03 302 查看
下面是一个用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;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: