本項目實現完整的學生信息增刪改查、統計、排序、文件持久化存儲,採用結構體數組 + 二進制文件架構,適合初學者理解「數據結構 + 文件操作 + 模塊化程式設計」。
#define MAX_STU 300
typedef struct {
char name[60];
char id[7]; // 學號
int score; // 成績(單科示例)
} Student;
Student stu[MAX_STU]; // 全局數組作為內存數據庫
int g_count = 0; // 當前學生數
| 功能 | 函數 | 關鍵技術點 |
|---|---|---|
| 數據持久化 | load_data() / save_data() | fread/fwrite 二進制讀寫結構體數組 |
| 菜單系統 | show_menu() / main_loop() | switch-case 驅動,system("cls") 清屏 |
| 增刪改查 | add(), del(), modify(), query() | 線性查找、數組元素移動覆蓋刪除 |
| 統計排序 | statistics(), sort_by_score() | 冒泡排序(降序)、平均分計算 |
int load_data() {
FILE *fp = fopen("student.dat", "rb");
if (!fp) return 0; // 文件不存在視為空庫
int i = 0;
while (i < MAX_STU && fread(&stu[i], sizeof(Student), 1, fp) == 1) {
i++;
}
fclose(fp);
return i; // 返回實際讀取數量
}
void add_student() {
int n; printf("輸入添加人數: "); scanf("%d", &n);
for (int i = 0; i < n && g_count < MAX_STU; ++i) {
printf("姓名 學號 成績: ");
scanf("%59s %6s %d", stu[g_count].name, stu[g_count].id, &stu[g_count].score);
// 即時追加寫入文件
FILE *fp = fopen("student.dat", "ab");
fwrite(&stu[g_count], sizeof(Student), 1, fp);
fclose(fp);
g_count++;
}
}
void delete_by_name() {
char name[60]; printf("輸入姓名: "); scanf("%59s", name);
int found = -1;
for (int i = 0; i < g_count; ++i)
if (strcmp(stu[i].name, name) == 0) { found = i; break; }
if (found == -1) { puts("查無此人"); return; }
// 內存數組前移
for (int i = found; i < g_count - 1; ++i) stu[i] = stu[i + 1];
g_count--;
// 文件整體重寫(簡單粗暴但有效)
FILE *fp = fopen("student.dat", "wb");
for (int i = 0; i < g_count; ++i) fwrite(&stu[i], sizeof(Student), 1, fp);
fclose(fp);
puts("刪除成功");
}
void sort_desc() {
for (int i = 0; i < g_count - 1; ++i)
for (int j = 0; j < g_count - 1 - i; ++j)
if (stu[j].score < stu[j+1].score) {
Student tmp = stu[j]; stu[j] = stu[j+1]; stu[j+1] = tmp;
}
// 輸出前 N 名...
}
stu、g_count 封裝在結構體 SystemContext 中,作參數傳遞。scanf("%59s", ...) 防止緩衝區溢出;檢查 scanf 返回值。system("cls") 僅 Windows,Linux/Mac 用 system("clear"),建議封裝 clear_screen()。student.h/c, file_io.h/c, ui.h/c, main.c。這個系統雖屬「教學級」,但涵蓋了 C 語言核心技能:結構體、指針、文件操作、動態內存(固定數組模擬)、模塊化設計、交互邏輯。建議初學者先跑通,再按上述方向重構,體會「能跑」到「好維護」的演進。