Docs

Pseudocode reference

Reading and writing files

Open, read, write, and close text files in Cambridge-style pseudocode.

updated November 2, 2026

Four steps

Every file operation follows the same pattern.

  1. 1
    Declare
    The file name and data variables
  2. 2
    Open
    OPENFILE with FOR READ or FOR WRITE
  3. 3
    Read or write
    READFILE or WRITEFILE
  4. 4
    Close
    CLOSEFILE when you finish

Read a line

READFILE reads the next line of the file into a string variable.

Pseudocode
DECLARE FileName : STRING
DECLARE LineText : STRING

FileName <- "Scores.txt"
OPENFILE FileName FOR READ
READFILE FileName, LineText
OUTPUT "First line: ", LineText
CLOSEFILE FileName

Write a line

WRITEFILE writes a line to a file opened FOR WRITE.

Pseudocode
DECLARE FileName : STRING

FileName <- "Scores.txt"
OPENFILE FileName FOR WRITE
WRITEFILE FileName, "Mai,42"
CLOSEFILE FileName

Watch out. Don't open the same file for READ and WRITE at the same time, and always close a file, even in a short algorithm.