作业练习题
有如下结构体
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;
};
申请该结构体数组,容量为5,初始化5个学生的信息
使用fprintf将数组中的5个学生信息,保存到文件中去
下一次程序运行的时候,使用fscanf,将文件中的5个学生信息,写入(加载)到数组中去,并直接输出学生信息
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.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>
int main(int argc, const char *argv[])
{
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;
};
// 创建并初始化结构体数组
struct Student students[5] = {
{"张三", 20, 90.5, 85.5, 88.0, 92.0, 87.0, 90.0},
{"李四", 21, 85.0, 90.0, 88.5, 89.0, 91.0, 88.0},
{"王五", 22, 88.0, 89.0, 90.0, 87.0, 86.0, 91.0},
{"赵六", 23, 86.0, 88.0, 87.0, 90.0, 89.0, 92.0},
{"孙七", 24, 87.0, 86.0, 85.0, 88.0, 90.0, 91.0},
};
// 将学生信息写入文件
FILE* fp = fopen("506zy1.txt", "w");
if (fp == NULL) {
printf("无法打开文件\n");
return -1;
}
for (int i = 0; i < 5; i++)
{
fprintf(fp, "%s %d %.1lf %.1lf %.1lf %.1lf %.1lf %.1lf\n",students[i].\
name,students[i].age,students[i].math_score,students[i].\
chinese_score,students[i].english_score,students[i].\
physics_score,students[i].chemistry_score,students[i].bio_score);
}
fclose(fp);
// 从文件中读取学生信息并加载到数组中
struct Student loaded_students[5];
fp = fopen("506zy1.txt", "r");
if (fp == NULL)
{
printf("无法打开文件\n");
return -1;
}
for (int i = 0; i < 5; i++)
{
fscanf(fp, "%s %d %lf %lf %lf %lf %lf %lf\n",loaded_students[i].name,\
&loaded_students[i].age,&loaded_students[i].math_score,\
&loaded_students[i].chinese_score,&loaded_students[i].english_score,\
&loaded_students[i].physics_score,&loaded_students[i].chemistry_score,\
&loaded_students[i].bio_score);
}
fclose(fp);
// 输出学生信息
for (int i = 0; i < 5; i++)
{
printf("姓名:%s 年龄:%d 数学成绩:%.1lf 语文成绩:%.1lf 英语成绩:%.1lf 物理成绩:%.1lf 化学成绩:%.1lf 生物成绩:%.1lf\n",\
loaded_students[i].name,loaded_students[i].age,\
loaded_students[i].math_score,loaded_students[i].chinese_score,\
loaded_students[i].english_score,loaded_students[i].physics_score,\
loaded_students[i].chemistry_score,loaded_students[i].bio_score);
}
return 0;
}