题目:
申请该结构体数组,容量为5,初始化5个学生的信息
使用fprintf将数组中的5个学生信息,保存到文件中去
下一次程序运行的时候,使用fscanf,将文件中的5个学生信息,写入(加载)到数组中去,并直接输出学生信息
代码:
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <pthread.h>
#include <semaphore.h>
#include <wait.h>
#include <signal.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <semaphore.h>
#include <sys/msg.h>
#include <sys/shm.h>
#include <sys/un.h>
//定义结构体
typedef struct Student{
char name[16];
int age;
double math_score;
double chinese_score;
double english_score;
double physics_score;
double chemistry_score;
double bio_score;
}stu;
//将结构体数组信息存入文件
void save_stu(stu* stu,int len)
{
FILE *wf=fopen("s1.txt","w");
if(wf==NULL)
{
perror("wf");
return;
}
for(int i=0;i<len;i++)
{
fprintf(wf,"%s\t",stu[i].name);
fprintf(wf,"%d\t",stu[i].age);
fprintf(wf,"%.2lf\t",stu[i].math_score);
fprintf(wf,"%.2lf\t",stu[i].chinese_score);
fprintf(wf,"%.2lf\t",stu[i].english_score);
fprintf(wf,"%.2lf\t",stu[i].physics_score);
fprintf(wf,"%.2lf\t",stu[i].chemistry_score);
fprintf(wf,"%.2lf\t",stu[i].bio_score);
fprintf(wf,"\n");
}
fclose(wf);
}
//将文件中的内容读取到结构体数组中
void load_stu(stu* stu)
{
FILE* rf=fopen("./s1.txt","r");
int i=0;
while(1)
{
int retval=fscanf(rf,"%s %d %lf %lf %lf %lf %lf %lf\n",stu[i].name,&stu[i].age,&stu[i].math_score,&stu[i].chinese_score\
,&stu[i].english_score,&stu[i].physics_score,&stu[i].chemistry_score,&stu[i].bio_score);
if(retval == EOF)
break;
i++;
}
fclose(rf);
}
//输出结构体数组中的信息
void show_stu(stu* stu,int len)
{
for(int i=0;i<len;i++)
{
//%g:打印小数点后的有效位,仅printf可用
printf("name:%s,age:%d,chinese_score=%g,english_score=%g,physics_score=%g,chemistry_score=%g,bio_score=%g\n",\
stu[i].name,stu[i].age,stu[i].chinese_score,stu[i].english_score,stu[i].physics_score\
,stu[i].chemistry_score,stu[i].bio_score);
}
}
int main(int argc, const char *argv[])
{
stu stu1[5]={{"zhao1",30,88,100,60,80,90,88},{"li2",27,99,88,77,78,89,90},{"liu3",33,99,88,70,88,91,80}\
,{"zhu4",38,80,66,76,74,83,70},{"liu1",40,74,81,73,72,67,70}};
save_stu(stu1,5);
stu stu2[5];
load_stu(stu2);
show_stu(stu2,5);
return 0;
}