一、实验目的
通过本次实验对一个班级学生成绩的管理,使学生了解文件的主要操作。详细的目标如下:
二、实验内容
三、实验步骤
- 利用磁盘文件对学生成绩进行管理:
- #include
- #include
- #include
-
- struct Score {
- char name[20];
- int math_score;
- int english_score;
- };
-
- int main() {
- FILE* fp;
- struct Score score;
- char query_name[20];
- int found = 0;
-
- // 打开文件
- fp = fopen("score.dat", "rb");
-
- if (fp == NULL) {
- printf("Failed to open file\n");
- exit(1);
- }
-
- // 读取数据
- while (fread(&score, sizeof(struct Score), 1, fp) > 0) {
- if (strcmp(score.name, query_name) == 0) {
- printf("%s's scores: Math: %d, English: %d\n",
- score.name, score.math_score, score.english_score);
- found = 1;
- break;
- }
- }
-
- // 关闭文件
- fclose(fp);
-
- if (!found) {
- printf("Score not found.\n");
- }
-
- return 0;
- }
2.修改成绩:
- #include
- #include
- #include
-
- struct Score {
- char name[20];
- int math_score;
- int english_score;
- };
-
- int main() {
- FILE* fp;
- struct Score score;
- char modify_name[20];
- int found = 0, modify_math_score, modify_english_score;
-
- // 打开文件
- fp = fopen("score.dat", "r+b");
-
- if (fp == NULL) {
- printf("Failed to open file\n");
- exit(1);
- }
-
- // 修改数据
- while (fread(&score, sizeof(struct Score), 1, fp) > 0) {
- if (strcmp(score.name, modify_name) == 0) {
- found = 1;
- printf("%s's scores: Math: %d, English: %d\n",
- score.name, score.math_score, score.english_score);
-
- printf("Enter new math score:");
- scanf("%d", &modify_math_score);
- printf("Enter new english score:");
- scanf("%d", &modify_english_score);
-
- score.math_score = modify_math_score;
- score.english_score = modify_english_score;
-
- fseek(fp, -sizeof(struct Score), SEEK_CUR);
- fwrite(&score, sizeof(struct Score), 1, fp);
- break;
- }
- }
-
- // 关闭文件
- fclose(fp);
-
- if (!found) {
- printf("Score not found.\n");
- } else {
- printf("Score modified.\n");
- }
-
- return 0;
- }
3.显示所有学生成绩
- #include
- #include
- #include
-
- struct Score {