Skip to content

9618 · 10.3

Files — practice questions

Practice and worked examples for 9618 Files. Short previews only — attempt the full question in MarkScheme against the official scheme.

Worked example 1

A text file, Scores.txt, contains a list of scores, one per line. Write pseudocode to read all the scores from the file, calculate their total, and output the final total.

File Content (Scores.txt):

150
230
95
Show solution outline
// 1. Initialise variables
DECLARE TotalScore : INTEGER
DECLARE CurrentScore : INTEGER
TotalScore <- 0

// 2. Open file for reading
OPENFILE "Scores.txt" FOR READ

// 3. Loop until the end of the file
WHILE NOT EOF("Scores.txt")
    // 4. Read a line and add to total
    READFILE "Scores.txt", CurrentScore
    TotalScore <- TotalScore + CurrentScore
ENDWHILE

// 5. Close the file
CLOSEFILE "Scores.txt"

// 6. Output the result
OUTPUT "Total score is: ", TotalScore

Mark Scheme:

  • 1 mark for initialising TotalScore.
  • 1 mark for opening the file in READ mode.
  • 1 mark for a correct loop condition (WHILE NOT EOF).
  • 1 mark for correctly reading from the file inside the loop.
  • 1 mark for correctly accumulating the total inside the loop.
  • 1 mark for closing the file.

Expected Output: Total score is: 475

Worked example 2

A programme needs to save a new user's username to a file called Users.txt. The username is stored in a variable NewUser. The programme should add this new user to the end of the list without deleting existing users. Write the pseudocode to accomplish this.

Initial File Content (Users.txt):

Alice
Bob

Variable Value: NewUser="Charlie"NewUser = "Charlie"

Show solution outline
DECLARE NewUser : STRING
NewUser <- "Charlie"

// 1. Open file in APPEND mode to add to the end
OPENFILE "Users.txt" FOR APPEND

// 2. Write the new data to the file
WRITEFILE "Users.txt", NewUser

// 3. Close the file to save the changes
CLOSEFILE "Users.txt"

Mark Scheme:

  • 1 mark for opening the file in APPEND mode (using WRITE would be incorrect and lose the mark).
  • 1 mark for writing the correct variable (NewUser) to the file.
  • 1 mark for closing the file.

Final File Content (Users.txt):

Alice
Bob
Charlie