有如下结构体
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>
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;
};
int main() {
// 定义并初始化结构体数组
struct Student students[5] = {
{"Alice", 18, 85.5, 90.0, 80.0, 88.0, 92.0, 88.5},
{"Bob", 19, 90.0, 85.0, 88.0, 92.0, 88.0, 90.5},
{"Charlie", 20, 88.0, 80.0, 92.0, 85.0, 90.0, 87.0},
{"David", 18, 92.0, 90.0, 85.0, 80.0, 88.0, 92.0},
{"Eve", 17, 80.0, 88.0, 90.0, 92.0, 85.0, 80.0}
};
// 保存到文件
FILE *file = fopen("students.txt", "w");
if (file == NULL) {
perror("Failed to open file");
return 1;
}
for (int i = 0; i < 5; ++i) {
fprintf(file, "Name: %s, Age: %d, Math: %.2f, Chinese: %.2f, English: %.2f, Physics: %.2f, Chemistry: %.2f, Biology: %.2f\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(file);
// 假设程序重新运行,从文件中读取学生信息
// 重新初始化数组(实际场景中可能不需要,但为了演示完整性)
memset(students, 0, sizeof(students));
file = fopen("students.txt", "r");
if (file == NULL) {
perror("Failed to open file");
return 1;
}
for (int i = 0; i < 5; ++i) {
if (fscanf(file, "Name: %15s, Age: %d, Math: %lf, Chinese: %lf, English: %lf, Physics: %lf, Chemistry: %lf, Biology: %lf\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) != 8) {
fprintf(stderr, "Failed to read student %d\n", i);
break; // 读取失败,退出循环
}
}
fclose(file);
// 输出学生信息
for (int i = 0; i < 5; ++i) {
printf("Student %d: Name=%s, Age=%d, Math=%.2f, Chinese=%.2f, English=%.2f, Physics=%.2f, Chemistry=%.2f, Biology=%.2f\n",
i + 1, 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].