File handling Cambridge IGCSE Computer Science (9–1) revision

Not started

Learn it

In plain words

Everything a program holds in its variables disappears the moment it stops. If the data is needed again tomorrow, the program must write it to a file on secondary storage, and read it back when it next runs.

5 things to know

  1. Data is stored in a file so that it is not lost when the program ends. It can be used again by the same program, or by another one.
  2. A file must be opened before it is used: OPENFILE "Scores.txt" FOR READ, or OPENFILE "Scores.txt" FOR WRITE.
  3. READFILE "Scores.txt", Line reads one line of text from the file into the variable Line.
  4. WRITEFILE "Scores.txt", Line writes the contents of the variable Line to the file.
  5. CLOSEFILE "Scores.txt" closes the file when the program has finished with it.

Worked example

A game must save the player's high score so that it is still there the next time the game is played. Describe the pseudocode steps.

  1. Open the file for writing: OPENFILE "HighScore.txt" FOR WRITE.
  2. Write the value: WRITEFILE "HighScore.txt", HighScore.
  3. Close the file: CLOSEFILE "HighScore.txt".

Tips and tricks

  • The order is always open, then read or write, then close. A file opened FOR READ cannot be written to.
  • "So that the data is not lost when the program ends" is the reason for using a file. Variables are held in RAM.
5 questions, about 2 minutes.

It lands in your notebook with its questions as flashcards.

File handling: 5 questions and answers

These are the quiz’s questions. Do the quiz first, then come back here for the ones that got you.

  1. Why is data stored in a file?
    • to make the program shorter
    • so that it is kept after the program ends (the answer)
    • to make the screen brighter
    • to speed up the processor

    Variables are lost when the program stops.

  2. Which statement must come before reading from a file?
    • CLOSEFILE
    • OPENFILE (the answer)
    • WRITEFILE
    • DECLARE

    A file has to be opened before it can be used.

  3. What does READFILE "Data.txt", Line do?
    • deletes a line from the file
    • reads a line of text from the file into the variable Line (the answer)
    • writes Line to the file
    • closes the file

    The data moves from the file into the variable.

  4. What does WRITEFILE "Data.txt", Line do?
    • reads a line into the variable
    • writes the contents of the variable Line to the file (the answer)
    • opens the file
    • renames the file

    The data moves from the variable into the file.

  5. What should be done when a program has finished using a file?
    • delete it
    • open it again
    • close it (the answer)
    • print it

    CLOSEFILE "Data.txt".

Still stuck on this one?Ask in the Papermunch Discord, or help someone else who is. Discord is for ages 13 and up.Join the server

Things you can type

Or go straight to

Or browse a shelf