1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149
| #include #include #include
#define FILENAME "students.dat"
struct Student { int id; char name[50]; float score; };
// 添加学生 void addStudent() { FILE *fp = fopen(FILENAME, "ab"); if (fp == NULL) { printf("无法打开文件!\n"); return; }
struct Student s; printf("学号:"); scanf("%d", &s.id); printf("姓名:"); scanf("%s", s.name); printf("成绩:"); scanf("%f", &s.score);
fwrite(&s, sizeof(struct Student), 1, fp); fclose(fp);
printf("添加成功!\n"); }
// 显示所有学生 void displayStudents() { FILE *fp = fopen(FILENAME, "rb"); if (fp == NULL) { printf("暂无学生信息!\n"); return; }
struct Student s; printf("\n%-10s %-20s %s\n", "学号", "姓名", "成绩"); printf("--------------------------------\n");
while (fread(&s, sizeof(struct Student), 1, fp) == 1) { printf("%-10d %-20s %.2f\n", s.id, s.name, s.score); }
fclose(fp); }
// 查找学生 void searchStudent() { int id; printf("请输入学号:"); scanf("%d", &id);
FILE *fp = fopen(FILENAME, "rb"); if (fp == NULL) { printf("文件不存在!\n"); return; }
struct Student s; int found = 0;
while (fread(&s, sizeof(struct Student), 1, fp) == 1) { if (s.id == id) { printf("\n找到学生:\n"); printf("学号:%d\n", s.id); printf("姓名:%s\n", s.name); printf("成绩:%.2f\n", s.score); found = 1; break; } }
if (!found) { printf("未找到该学生!\n"); }
fclose(fp); }
// 修改学生成绩 void updateScore() { int id; printf("请输入学号:"); scanf("%d", &id);
FILE *fp = fopen(FILENAME, "rb+"); if (fp == NULL) { printf("文件不存在!\n"); return; }
struct Student s; int found = 0;
while (fread(&s, sizeof(struct Student), 1, fp) == 1) { if (s.id == id) { printf("当前成绩:%.2f\n", s.score); printf("新成绩:"); scanf("%f", &s.score);
// 移动回该记录的起始位置 fseek(fp, -sizeof(struct Student), SEEK_CUR); fwrite(&s, sizeof(struct Student), 1, fp);
printf("修改成功!\n"); found = 1; break; } }
if (!found) { printf("未找到该学生!\n"); }
fclose(fp); }
int main() { int choice;
while (1) { printf("\n===== 学生成绩管理系统 =====\n"); printf("1. 添加学生\n"); printf("2. 显示所有学生\n"); printf("3. 查找学生\n"); printf("4. 修改成绩\n"); printf("5. 退出\n"); printf("请选择:"); scanf("%d", &choice);
switch (choice) { case 1: addStudent(); break; case 2: displayStudents(); break; case 3: searchStudent(); break; case 4: updateScore(); break; case 5: return 0; default: printf("无效选择!\n"); } }
return 0; }
|