向文件中的结构体写数据

windows vc++6.0下通过;
功能:在文件的结构体中写入,读取数据。

#include<stdio.h>
////////////////////////////////////////////函数声明//////////////////////////////////////////////////////
void put_in();
void get_out();
struct student
////////////////////////////////////////////结构体定义////////////////////////////////////////////////////////
{char name[10];
int score;
}




main()
{
printf("record data access!\n\n");
put_in();
get_out();

}
//////////////////////////////////////////////写入数据函数//////////////////////////////////////////////////
void put_in()
{
FILE *fp;
struct student stud[]={{"张三",67},{"李四",78},{"王五",89}};
if((fp=fopen("stud.dat","wb"))==NULL)
{
printf("Cannot creat stud.dat!\n");
exit(1);
}   
fwrite(stud,sizeof(struct student),3,fp);
fclose(fp);
printf("ok\n");
}


/////////////////////////////////////////读取数据函数//////////////////////////////////////////////////
void get_out()
{

FILE *fp;
struct student stud[6];
int i;
if((fp=fopen("stud.dat","rb"))==NULL)
{
printf("Cannot open stud.dat!\n");exit(1);
}
fread(stud,sizeof(struct student),3,fp);
printf("姓名\t成绩\n");
printf("----\t----\n");
for(i=0;i<3;i++)
printf("%s\t%d\n",stud[i].name,stud[i].score);
printf("\n");
fclose(fp);
}

这里写图片描述

这里写图片描述

猜你喜欢

转载自blog.csdn.net/weixin_42828324/article/details/81290429