// 保存数据到文件
void saveToFile(Student* head, const char* filename) {
FILE* file = fopen(filename, "w");
if (file == NULL) {
printf("无法打开文件 %s 进行写入。\n", filename);
return;
}
while (head != NULL) {
fprintf(file, "%s %d %.2f\n", head->name, head->id, head->score);
head = head->next;
}
fclose(file);
}
// 从文件加载数据
void loadFromFile(Student** head, const char* filename) {
FILE* file = fopen(filename, "r");
if (file == NULL) {
// printf("无法打开文件 %s 进行读取。\n", filename);
return;
}
char name[50];
int id;
float score;
while (fscanf(file, "%s %d %f", name, &id, &score) == 3) {
insertStudent(head, name, id, score);
}
fclose(file);
}
int main() {
Student* head = NULL;
int choice;
char name[50];
int id;
float score;
const char* filename = "students.txt";
// 从文件加载数据
loadFromFile(&head, filename);
do {
// 显示菜单
printf("学生成绩管理系统\n");
printf("1. 添加学生\n");
printf("2. 显示学生信息\n");
printf("3. 查找学生\n");
printf("4. 删除学生\n");
printf("5. 修改学生信息\n");
printf("6. 保存数据到文件\n");
printf("7. 退出\n");
printf("请选择操作(1-7): ");
scanf("%d", &choice);
switch (choice) {
case 1:
// 添加学生
printf("请输入学生姓名: ");
scanf("%s", name);
printf("请输入学生学号: ");
scanf("%d", &id);
printf("请输入学生成绩: ");
scanf("%f", &score);
insertStudent(&head, name, id, score);
break;
case 2:
// 显示学生信息
displayStudents(head);
break;
case 3:
// 查找学生
printf("请输入要查找的学生学号: ");
scanf("%d", &id);
Student* foundStudent = findStudentById(head, id);
if (foundStudent != NULL) {
printf("学生信息找到:\n");
printf("%-20s %-10s %-10s\n", "姓名", "学号", "成绩");
printf("-------------------------------------------\n");
printf("%-20s %-10d %-10.2f\n", foundStudent->name, foundStudent->id, foundStudent->score);
} else {
printf("未找到该学生。\n");
}
break;
case 4:
// 删除学生
printf("请输入要删除的学生学号: ");
scanf("%d", &id);
deleteStudentById(&head, id);
break;
case 5:
// 修改学生信息
printf("请输入要修改的学生学号: ");
scanf("%d", &id);
updateStudentById(head, id);
break;
case 6:
// 保存数据到文件
saveToFile(head, filename);
printf("学生信息已保存到文件 %s 中。\n", filename);
break;
case 7:
// 退出程序,释放内存
freeList(head);
break;
default:
printf("无效的选择,请重新输入。\n");
}
printf("\n");
} while (choice != 7);
return 0;
}