此页面需较新浏览器(支持 SharedArrayBuffer)。请升级 Chrome、Edge、Firefox 或 Safari 至最新版本。
文件让数据在程序结束后保留
- 文件把数据存在磁盘上,所以程序停止之后它还在。
- 你通过一个
FILE *来操作文件 —— 这是fopen给你的一个指针。 - 在这些任务里,你先写一个文件,再在同一个程序里把它读回来,所以一切都是自包含的。
探索
Writing then reading a file
A file is used in three steps: 开放的 it with fopen, read or write, then 关闭 it with fclose.
打开与关闭
fopen("data.txt", "w")以写入方式打开文件(它会创建文件或清空文件)。fopen("data.txt", "r")以读取方式打开。- 用完后总是
fclose(f),这样数据才会保存,文件才会被释放。
用 fprintf 写入
fprintf和printf很像,只是它的第一个参数是FILE *。fprintf(f, "%d\n", x);把数字x和一个换行写进文件f。- 每个值单独写一行,这样读回来时更容易。
用 fscanf 和 fgets 读取
fscanf(f, "%d", &x)读一个数字;成功时返回1。fgets(buf, size, f)读一行文本到buf;到末尾时返回NULL。- 循环直到读取失败,就能处理整个文件。
English
#include <stdio.h>
int main(void) {
FILE *f = fopen("nums.txt", "w");
fprintf(f, "3\n4\n");
fclose(f);
f = fopen("nums.txt", "r");
if (f == NULL) { // the file could not be opened
printf("cannot open nums.txt\n");
return 1;
}
int x, total = 0;
while (fscanf(f, "%d", &x) == 1) {
total += x;
}
fclose(f);
printf("%d\n", total); // 7
return 0;
}
常见错误
- 读写前先检查
fopen没有返回NULL。 - 用完一定要
fclose。
现在轮到你
- 这些任务是完整的程序:在
main里面写代码,用 Check answer(检查答案) 来测试输出。 - 先写文件,
fclose它,然后再打开来读取,循环直到读取失败。
难度 3/5 · 今日首次完成可获 200 金币及少量额外奖励
In main: write the numbers 10, 20, 5, 7 (one per line) to a file, close it, then open it again and add them up with fscanf. Print the total (42).
点击“运行”查看此处输出。
难度 3/5 · 今日首次完成可获 200 金币及少量额外奖励
In main: write three lines of text to a file, close it, then open it again and count the lines with fgets. Print the count (3).
点击“运行”查看此处输出。
难度 3/5 · 今日首次完成可获 200 金币及少量额外奖励
Mode "w" wipes a file; mode "a" appends to the end. The starter writes 10 and 20. Reopen scores.txt with "a", add the line 30, close it, then read every number back and print the total (60).
点击“运行”查看此处输出。