Skip to content

Text files

C Programming Lesson 19 2:30 English narration · English + 中文 subtitles burned in

space play · ←/→ 5s · j/l 10s · f fullscreen · ,/. speed

Chapters

Transcript
Everything you have written so far lives entirely in memory, so when the program ends, all of it disappears with it. 你目前写过的一切都完全活在内存里, 所以程序一结束,它们就随之消失了。
A file is different. 文件不一样。
It sits on disk, and it survives the program — that is the whole point of one. 它躺在磁盘上,能活过这个程序—— 这正是文件存在的意义。
Write your results to a file and they are still there tomorrow, and any other program can read them. 把结果写进文件,明天它们还在, 而且任何别的程序都能把它们读出来。
Both tasks in this lesson are the same round trip. 这一课的两道题都是同一个来回。
Fopen with the mode w opens it for writing, and be careful — that empties the file first. 用 "w" 模式 fopen 打开文件用于写入, 要小心——这会先把文件清空。
Fprintf is exactly printf with the file as an extra first argument, so put each value on its own line. fprintf 就是 printf,只是多了一个文件参数放在最前面, 所以把每个值各写一行。
Then close it, and open it a second time, now with the mode r. 然后关掉它,再第二次打开,这次用 "r" 模式。
The mode is fixed when you open, which is why the close in the middle is not optional. 模式是在打开的那一刻定下的, 所以中间那个 fclose 不是可有可无的。
Reading is where beginners get stuck, and the fix is to let the read itself tell you when to stop. 读取是初学者最容易卡住的地方, 而解决办法是让“读取”这个动作自己告诉你什么时候停。
Fscanf returns one when it successfully read a number. fscanf 成功读到一个数时返回 1。
Fgets hands back null when there is no line left. fgets 在没有下一行时交回 NULL。
So the loop condition is the end-of-file test: keep going until the read fails. 所以循环条件就是文件结束的判断:一直读到读取失败为止。
One more detail — fscanf wants an address, so it is ampersand x, not x, exactly as it was with scanf from the keyboard. 还有一个细节——fscanf 要的是地址, 所以要写 &x,不是 x, 和当初从键盘读入的 scanf 完全一样。
Now the first task. 现在做第一道题。
Open a file for writing and fprintf ten, twenty, five and seven, one per line, then close it. 打开一个文件用于写入,用 fprintf 写下 10、20、5、7,每个一行,然后关闭。
Open it for reading. 再打开它用于读取。
Loop with fscanf, adding them as you go, and close it again. 用 fscanf 循环,一边读一边累加,读完再关闭。
Then print the total, which is forty-two. 然后打印总和,也就是 42。
Note that these two tasks are whole programs — you write inside main, and the checker grades what you print. 注意这两道题都是完整的程序—— 你在 main 里面写,检查器根据你打印出来的内容评分。
Four things to take with you. 带走四点。
One: fopen gives you a FILE pointer, and the mode picks reading or writing. 第一:fopen 给你一个 FILE 指针,模式决定是读还是写。
Two: fprintf writes to a file exactly as printf writes to the screen. 第二:fprintf 写进文件,就像 printf 写到屏幕一样。
Three: loop until fscanf or fgets fails — that is the end of the file. 第三:一直循环到 fscanf 或 fgets 失败为止——那就是文件的结尾。
Four: fclose every file you open, or your data may never be saved. 第四:每一个打开的文件都要 fclose,否则你的数据可能根本没被保存。
Now do both tasks; the second one counts lines with fgets. 现在两道题都做一下;第二题是用 fgets 数行数。

Log in or create account

IGCSE, A-Level & AP