Text files · 文本文件
This page needs a recent browser (with SharedArrayBuffer support). Please update Chrome, Edge, Firefox or Safari to the latest version. · 此页面需较新浏览器(支持 SharedArrayBuffer)。请升级 Chrome、Edge、Firefox 或 Safari 至最新版本。
English
Open, then read or write
- AS topic 10.3 asks for pseudocode that handles a text file of one or more lines.
- Open the file in one mode:
READ,WRITEorAPPEND. WRITEstarts a new file and loses what was there.APPENDadds after what is there.CLOSEFILEwhen you have finished. A file is open in only one mode at a time.
中文
先打开,再读或写
- AS 主题 10.3 要求用伪代码处理由一行或多行组成的文本文件。
- 以一种模式打开文件:
READ、WRITE或APPEND。 WRITE新建文件,原有内容丢失。APPEND加在原有内容之后。- 用完后
CLOSEFILE。一个文件一次只能以一种模式打开。
OPENFILE "Note.txt" FOR WRITE
WRITEFILE "Note.txt", "Hello"
CLOSEFILE "Note.txt"
DECLARE LineOfText : STRING
OPENFILE "Note.txt" FOR READ
READFILE "Note.txt", LineOfText
CLOSEFILE "Note.txt"
OUTPUT LineOfText
English
EOF tells you when to stop
EOF("Note.txt")isTRUEwhen there is no further line to read.WHILE NOT EOF(...)reads every line.READFILEputs the next line into aSTRING.
中文
EOF 告诉你何时停止
- 没有下一行可读时,
EOF("Note.txt")为TRUE。 WHILE NOT EOF(...)读出每一行。READFILE把下一行放进一个STRING。
OPENFILE "List.txt" FOR WRITE
WRITEFILE "List.txt", "a"
WRITEFILE "List.txt", "b"
CLOSEFILE "List.txt"
DECLARE LineOfText : STRING
OPENFILE "List.txt" FOR READ
WHILE NOT EOF("List.txt")
READFILE "List.txt", LineOfText
OUTPUT LineOfText
ENDWHILE
CLOSEFILE "List.txt"
English
Watch out
- Declare the string before
READFILEuses it. - Random files (
OPENFILE … FOR RANDOM) are A2. This lesson does not use them.
中文
注意
- 在
READFILE使用变量之前,先声明这个字符串。 - 随机文件(
OPENFILE … FOR RANDOM)是 A2。这一课不用它们。
English
Common mistakes
- Read with
READFILEonly afterOPENFILE … FOR READ. WRITEreplaces the file. UseAPPENDto keep the old lines.
中文
常见错误
- 只有在
OPENFILE … FOR READ之后才能READFILE。 WRITE会替换文件。要保留旧行,用APPEND。
English
Now you try
- Write two lines, then read them back until
EOF.
中文
现在你来试
- 写入两行,再一直读到
EOF。
Write Hello to · 到 Note.txt, read it back into LineOfText, and output it. · 把 Hello 写入 Note.txt,读回 LineOfText,并输出它。
Click Run to see the output here. · 点击“运行”查看此处输出。
Write a and b to · 到 List.txt, then output both lines using WHILE NOT EOF. · 把 a 和 b 写入 List.txt,再用 WHILE NOT EOF 把两行都输出。
Click Run to see the output here. · 点击“运行”查看此处输出。
Write one to · 到 Note.txt, close it, APPEND the line two, then read both lines with WHILE NOT EOF and output them. · 把 one 写入 Note.txt 并关闭,再用 APPEND 加上一行 two,然后用 WHILE NOT EOF 读出两行并输出。
Click Run to see the output here. · 点击“运行”查看此处输出。