文件操作与实战
C 用 FILE * 指针操作文件:fopen 打开、fprintf/fscanf 读写、fclose 关闭。文件操作完必须关闭,否则数据可能没写入。
打开模式
- "r":只读(文件必须存在)
- "w":只写(清空原内容)
- "a":追加
- "r+" / "w+":读写
实战:学生成绩系统
把学生数据写入文件,再读出来。这是一个经典的 C 入门实战。
代码示例
#include <stdio.h>
typedef struct {
char name[20];
int score;
} Student;
int main() {
FILE *fp;
Student students[3] = {
{"张三", 90}, {"李四", 85}, {"王五", 78}
};
// 写入文件
fp = fopen("scores.txt", "w");
if (fp == NULL) {
printf("打开文件失败\n");
return 1;
}
for (int i = 0; i < 3; i++) {
fprintf(fp, "%s %d\n", students[i].name, students[i].score);
}
fclose(fp);
// 读取文件
fp = fopen("scores.txt", "r");
char name[20];
int score;
printf("=== 成绩单 ===\n");
while (fscanf(fp, "%s %d", name, &score) == 2) {
printf("%s: %d 分\n", name, score);
}
fclose(fp);
return 0;
}