有如下结构体: typedef struct Student{
char name[20];
int id;
double chinese;//语文成绩
double math;
double english;
double physical;
double chemical;
double biological;
}stu_t;
有一个 stu_t的结构体数组 arr[3];
随便使用任何方式初始化这个数组中的3个结构体
编写2个函数 :save_stu 和 load_stu save_stu:
通过 fprintf 将arr数组中的3个学生的所有信息,保存到文件中去 load_stu:通过 fscanf 将文件中的3个学生的所有信息,读取到一个新的结构体数组中,并输出所有学生的信息
#include<myhead.h>
typedef struct sockaddr_in addr_in_t;
typedef struct sockaddr addr_t;
typedef struct sockaddr_un addr_un_t;
typedef struct Student{
char name[20];
int id;
double chinese;
double math;
double english;
double physical;
double chemical;
double biological;
}stu_t;
int save_stu(stu_t arr[])
{
FILE* fp=fopen("3.txt","w");
if(fp==NULL)
{
perror("fopen");
return 1;
}
for(int i=0;i<3;i++)
{
fprintf(fp,"%s %d %.2lf %.2lf %.2lf %.2lf %.2lf %.2lf\n",arr[i].name,arr[i].id,
arr[i].chinese,arr[i].math,arr[i].english,arr[i].physical,
arr[i].chemical,arr[i].biological);
}
fclose(fp);
return 0;
}
int load_stu(stu_t brr[])
{
FILE* fp=fopen("3.txt","r");
if(fp==NULL)
{
perror("fopen");
return 1;
}
for(int i=0;i<3;i++)
{
fscanf(fp,"%s %d %lf %lf %lf %lf %lf %lf",brr[i].name,&brr[i].id,
&brr[i].chinese,&brr[i].math,&brr[i].english,&brr[i].physical,
&brr[i].chemical,&brr[i].biological);
}
fclose(fp);
}
int main(int argc, const char *argv[])
{
stu_t arr[3] = {{"张三",1001,10.1,20.2,30.3,40.4,50.5,60.6},
{"李四",1002,10.2,20.3,30.4,40.5,50.6,60.7},
{"王五",1003,10.3,20.4,30.5,40.6,50.7,60.8}
};
stu_t brr[3];
save_stu(arr);
load_stu(brr);
printf("文件中学生信息为:\n");
for(int i=0;i<3;i++)
{
printf("%s %d %.2lf %.2lf %.2lf %.2lf %.2lf %.2lf\n",brr[i].name,brr[i].id,
brr[i].chinese,brr[i].math,brr[i].english,brr[i].physical,
brr[i].chemical,brr[i].biological);
}
return 0;
}