Paper 1 & 2 · Cambridge Pseudocode 试卷一与二 · 剑桥伪代码

8.3 · File handling

8.3 · 文件处理

Storing data in a file, and reading it back

把数据存储到文件中,再读回来

Variables vanish the moment the program ends. A file keeps the data on the disk, so the next run, or a different program, can pick it up. Four commands do the whole job.

变量在程序结束的那一刻就会消失。文件则把数据保存在磁盘上,这样下一次运行,或者另一个程序,都能取用它。四条命令就能完成全部工作。

Core for all candidates 所有考生均需掌握的核心内容 Covers 8.3.1, 8.3.2 涵盖 8.3.1、8.3.2 Turns up in the 15-mark Paper 2 question 会出现在试卷二的 15 分题中

Explainer · 8.3.1

讲解 · 8.3.1

Why a program stores data in a file

程序为什么要把数据存储到文件中

Isla’s library program counts how many books were returned today, works out the figure, prints it, and ends. Tomorrow she opens the program again and the count is gone. Every variable lived in RAM, and RAM is cleared when the program closes or the computer is switched off.

Isla 的图书馆程序统计今天归还了多少本书,算出这个数字,打印出来,然后结束。第二天她再次打开程序,这个数字已经不见了。每个变量都存在于 RAM 中,而 RAM 会在程序关闭或计算机关机时被清空。

A file is data written to storage (a disk or drive), where it stays after the program ends and after the machine is powered down. Save the count to a file today, and tomorrow’s run can read it straight back.

文件是写入存储介质(磁盘或驱动器)的数据,即使在程序结束后、机器关机后,它也会一直保留在那里。今天把统计数字保存到文件中,明天再运行程序时就能直接把它读回来。

Df

Storing data in a file makes it persistent: it survives the program closing and the computer switching off, unlike a variable.

把数据存储到文件中,能使它具有持久性:不像变量,它能在程序关闭、计算机关机之后依然存在。

When a question asks why a program uses a file, one reason is not enough. Have two or three ready: the data is kept permanently; the same program can read it back on a later run; and another program, or another computer, can use it too.

当题目问程序为什么使用文件时,一个理由是不够的。要准备好两三个:数据被永久保存;同一个程序在之后的运行中可以把它读回来;而且另一个程序,或另一台计算机,也能使用它。

Where files fit 文件适用的场景

Anything that must outlast one run belongs in a file: a saved high score, a list of members, yesterday’s totals, a log of what happened. If the program could just recalculate it every time, a file is not needed.

任何必须在一次运行之后仍然存在的东西都应该放进文件中:保存的最高分、会员名单、昨天的统计总数、发生过的事件日志。如果程序每次都能重新计算出来,就不需要文件。

Explainer · 8.3.2

讲解 · 8.3.2

The four file operations

四种文件操作

Cambridge pseudocode uses exactly four commands for files. The file is always named as a string, in quotes, and that name is the file identifier you pass to every command.

剑桥伪代码对文件恰好使用四条命令。文件始终以带引号的字符串命名,这个名称就是你传给每条命令的文件标识符。

Operation操作 Pseudocode伪代码 What it does作用
Open打开 OPENFILE "returns.txt" FOR READ
OPENFILE "returns.txt" FOR WRITE
Gets the file ready in one mode. Must come before any read or write. A file can be open in only one mode at a time. 以某一种模式让文件准备就绪。必须在任何读取或写入之前进行。一个文件同一时间只能以一种模式打开。
Read读取 READFILE "returns.txt", Value Copies the next item, or the next line of text, out of the file and into the variable Value. Needs READ mode. 把文件中的下一项数据,或下一行文本,复制到变量 Value 中。需要 READ 模式。
Write写入 WRITEFILE "returns.txt", Value Copies Value into the file. Needs WRITE mode. 把 Value 复制到文件中。需要 WRITE 模式。
Close关闭 CLOSEFILE "returns.txt" Finishes with the file. Do it as soon as you no longer need the file. No brackets. 结束对文件的使用。一旦不再需要该文件就应立即执行。不带括号。
!

Opening FOR WRITE starts an empty file. If returns.txt already held data, opening it FOR WRITE throws that data away and begins a fresh, blank file. Open FOR READ when you want to keep what is already there.

以 FOR WRITE 打开会启用一个空文件。如果 returns.txt 已经保存了数据,以 FOR WRITE 打开它会把那些数据全部丢弃,开始一个全新的空白文件。想保留已有内容时,要以 FOR READ 打开。

?

Single item or a line of text, same commands. WRITEFILE "notes.txt", Total stores one number; WRITEFILE "notes.txt", Message where Message is a whole sentence stores a line of text. Reading works the same way: READFILE puts whatever the file holds into the variable you name.

无论是单个数据项还是一整行文本,命令都一样。WRITEFILE "notes.txt", Total 保存一个数字;WRITEFILE "notes.txt", Message 中若 Message 是一整句话,则保存一行文本。读取的方式相同:READFILE 会把文件中保存的内容存入你指定的变量。

Worked example · 8.3.1 + 8.3.2

示例讲解 · 8.3.1 + 8.3.2

Write a value today, read it back tomorrow

今天写入一个值,明天把它读回来

Isla’s program saves today’s returned-books count to returns.txt at closing time. The next morning, a separate run of the program reads that number back to show yesterday’s total. Because the value went to a file, it is still there after the program closed overnight.

Isla 的程序在打烊时把今天归还书籍的统计数字保存到 returns.txt 中。第二天早上,程序另外运行一次,把那个数字读回来,以显示昨天的总数。因为这个值已经存入了文件,所以即使程序在夜间关闭过,它依然存在。

DECLARE ReturnedToday : INTEGER
DECLARE ReturnedYesterday : INTEGER

// closing time: save today's count
ReturnedToday ← 34
OPENFILE "returns.txt" FOR WRITE
WRITEFILE "returns.txt", ReturnedToday
CLOSEFILE "returns.txt"

// next morning, a new run: read it back
OPENFILE "returns.txt" FOR READ
READFILE "returns.txt", ReturnedYesterday
CLOSEFILE "returns.txt"
OUTPUT "Books returned yesterday: ", ReturnedYesterday
# closing time: save today's count
returned_today = 34
my_file = open("returns.txt", "w")
my_file.write(str(returned_today))
my_file.close()

# next morning, a new run: read it back
my_file = open("returns.txt", "r")
returned_yesterday = my_file.read()
my_file.close()
print("Books returned yesterday:", returned_yesterday)
' closing time: save today's count
Dim returnedToday As Integer = 34
Dim writer As New StreamWriter("returns.txt")
writer.WriteLine(returnedToday)
writer.Close()

' next morning, a new run: read it back
Dim reader As New StreamReader("returns.txt")
Dim returnedYesterday As String = reader.ReadLine()
reader.Close()
Console.WriteLine("Books returned yesterday: " & returnedYesterday)

Short file-handling questions are pseudocode only. Program code (Python, Java, Visual Basic) is accepted only in the 15-mark Paper 2 scenario question. Java file handling needs try/catch exception handling, which is outside the IGCSE syllabus, so it is not shown here.

简答式的文件处理题只接受伪代码。程序代码(Python、Java、Visual Basic)只在试卷二的 15 分情境题中被接受。Java 的文件处理需要 try/catch 异常处理,这不在 IGCSE 考纲范围内,因此这里不作展示。

Notice the shape repeats: open, do the one job, close. Then open again in the other mode for the next job. The file identifier "returns.txt" is written the same way in every command.

留意这个模式在不断重复:打开、完成一项任务、关闭。然后再以另一种模式打开,进行下一项任务。文件标识符 "returns.txt" 在每条命令中的写法都相同。

Step through

逐步演示

What each line does to the file and the variable

每一行对文件和变量做了什么

Click through the eight lines of the pseudocode above. Watch what is on the disk in returns.txt and what is in memory at each step.

依次点击浏览上方伪代码的八行。观察每一步中 returns.txt 磁盘上的内容,以及内存中的情况。

On the disk
磁盘上
In memory (variables)
内存中(变量)

Check your understanding

检验你的理解

A value is stored in scores.txt. Which line copies it into the variable Score?

一个值保存在 scores.txt 中。哪一行能把它复制到变量 Score 中?

Check your understanding

检验你的理解

members.txt already holds 40 names. The program runs OPENFILE "members.txt" FOR WRITE. What happens to the 40 names?

members.txt 中已经保存了 40 个名字。程序运行了 OPENFILE "members.txt" FOR WRITE。这 40 个名字会发生什么?

Common mistakes

常见错误

Markers reported these patterns for 8.3.1 / 8.3.2 考官针对 8.3.1 / 8.3.2 报告了以下模式

RecurringAsked why a program stores data in a file, many candidates gave one reason (the data is kept permanently) and could not give a second. Marks usually need two: it survives the program closing and the machine switching off, and the same program on a later run, or a different program, can read it back.

反复出现被问及为什么程序把数据存储到文件中时,许多考生只给出一个理由(数据被永久保存),却给不出第二个。通常需要两个理由才能得分:它能在程序关闭、机器关机后依然存在,并且同一个程序在之后的运行中,或另一个程序,都能把它读回来。

In a question matching each operation to its description, markers reported candidates choosing “open” for “retrieves data from a file”. Opening only gets the file ready in a mode. The operation that actually brings data out of the file is READFILE.

在把每种操作与其描述配对的题目中,考官报告称考生选择了"打开"来对应"从文件中取出数据"。打开只是让文件以某种模式准备就绪。真正把数据从文件中取出的操作是 READFILE。

On the code itself, watch the syntax: CLOSEFILE takes the file identifier with no brackets, and a file opened FOR WRITE cannot be read from until it is closed and re-opened FOR READ.

在代码本身方面,要注意语法:CLOSEFILE 接收文件标识符时不带括号,而以 FOR WRITE 打开的文件在被关闭并重新以 FOR READ 打开之前,无法被读取。

✕

Bracket syntax: CLOSEFILE(MyFile). The brackets are not part of Cambridge pseudocode, and MyFile here is not the quoted file identifier the other commands use.

括号语法: CLOSEFILE(MyFile)。括号不属于剑桥伪代码,并且这里的 MyFile 也不是其他命令所使用的带引号的文件标识符。

✓

Identifier, no brackets: CLOSEFILE "returns.txt", written the same way as in OPENFILE, READFILE and WRITEFILE.

标识符,不带括号: CLOSEFILE "returns.txt",写法与 OPENFILE、READFILE 和 WRITEFILE 中相同。

✕

One circular reason: “The data is stored in a file so the program can use the data.” That says nothing a variable would not also do.

一个循环理由:"数据存储到文件中,这样程序就能使用这些数据。"这话对变量同样成立,没有说出任何新信息。

✓

Two real reasons: “The count is saved to a file so it is still there after the program closes overnight, and the next morning’s run can read it back.”

两个真正的理由:"这个统计数字被保存到文件中,这样即使程序在夜间关闭,它依然存在,而且第二天早上运行程序时能把它读回来。"

✕

Wrong mode for the job: OPENFILE "returns.txt" FOR WRITE followed by READFILE "returns.txt", X. A file opened for writing cannot be read.

用错了模式: OPENFILE "returns.txt" FOR WRITE 之后紧跟 READFILE "returns.txt", X。以写入模式打开的文件是无法被读取的。

✓

Open in the mode you need: FOR READ before READFILE, FOR WRITE before WRITEFILE, and CLOSEFILE then OPENFILE again to switch modes.

以你需要的模式打开:在 READFILE 前用 FOR READ,在 WRITEFILE 前用 FOR WRITE,要切换模式则先 CLOSEFILE 再重新 OPENFILE。

Revision questions

复习题

Past-paper style. Write an answer, then reveal the marking points and mark yourself.

采用历年真题风格。写下答案,然后展开评分要点给自己打分。

Question 1 · 2 marks 第 1 题 · 2 分

[2]State two reasons a program might store its data in a file rather than only in variables.

[2]陈述程序把数据存储到文件中而不只存放于变量中的两个理由。

Question 2 · 1 mark 第 2 题 · 1 分

[1]Write the pseudocode statement to open a file called log.txt so that data can be written to it.

[1]写出打开名为 log.txt 的文件、以便向其写入数据的伪代码语句。

Question 3 · 3 marks 第 3 题 · 3 分

[3]Write pseudocode to write the contents of the variable Total to a file called results.txt, then close the file.

[3]编写伪代码,把变量 Total 的内容写入名为 results.txt 的文件,然后关闭该文件。

Question 4 · 4 marks 第 4 题 · 4 分

[4]Write pseudocode to read a single line of text from message.txt into a variable and output it.

[4]编写伪代码,从 message.txt 中读取一行文本到变量中,并将其输出。

Question 5 · 4 marks 第 5 题 · 4 分

[4]A program opens data.txt using FOR WRITE at the start of every run. Explain the problem this causes and how to fix it.

[4]某程序在每次运行开始时都用 FOR WRITE 打开 data.txt。解释这会造成什么问题,以及如何解决。

Flashcards

记忆卡片

Active recall for this subtopic’s key terms.

针对本子主题关键术语的主动回忆练习。

Prototype render · content grounded in the Cambridge IGCSE 0478 syllabus pseudocode guide and real 0478 examiner-report data for 8.3.1 / 8.3.2 · not yet wired to live routes