Write pseudocode to handle text files that consist of one or more lines

Topic 10.3 – Files

Learning Objective

Write correct pseudocode to handle text files that contain one or more lines, using the Cambridge 9618 conventions for opening, reading, writing, appending, detecting end‑of‑file (EOF) and closing files.

Why Use Files? (Purpose & Security)

  • Files give programmes permanent storage – data remain after the program terminates and can be shared between runs or different programmes.
  • They are the primary means of enforcing data‑integrity checks (e.g. validating input read from a file) and of applying security controls such as file‑access permissions.

File Modes

  • READ – opens an existing file for sequential reading; the file pointer starts at the first character.
  • WRITE – creates a new file (or overwrites an existing one) and positions the pointer at the beginning for sequential writing.
  • APPEND – opens an existing file and positions the pointer at the end; new data are added without disturbing the existing content (useful for log files).

Opening and Closing Files

All file operations are performed through a file handle. The handle is created with OPEN … AS and released with CLOSE. Never forget to close a file – even if the programme exits early (e.g. after an error) the CLOSE statement must be executed to flush buffers and release the lock.

Security Checklist (Data‑Integrity & Permissions)

  • Check existence before trying to read: IF FILEEXISTS(fileName) THEN …
  • Open only the required mode (READ, WRITE or APPEND) to minimise accidental overwriting or unauthorised access.
  • Validate data immediately after reading (e.g. confirm a line that should contain an integer really does).
  • Handle errors gracefully – if a file cannot be opened, display a clear message and RETURN after closing any already‑opened handles.

File‑Handling Operations (Cambridge 9618 Syntax)

OperationPseudocode SyntaxDescription
Open for readingOPEN fileName FOR READ AS fileCreates a handle file for sequential reading.
Open for writingOPEN fileName FOR WRITE AS fileCreates a new file (or overwrites an existing one) for sequential writing.
Open for appendingOPEN fileName FOR APPEND AS fileOpens an existing file and positions the pointer at the end.
Read a lineREADLINE file INTO lineReads the next line of text; if no more lines are available the EOF flag becomes true.
Write a lineWRITELINE file, lineWrites line followed by a newline character.
Test for end‑of‑fileEOF(file)Returns TRUE when the file pointer is positioned after the last line.
Close a fileCLOSE fileFlushes buffers and releases the handle.
Check existenceFILEEXISTS(fileName)Returns TRUE if the named file is present on disk.

Exam‑Ready Pseudocode Template

/*--- Template: read a text file line‑by‑line ---*/

OPEN "yourFile.txt" FOR READ AS f

WHILE NOT EOF(f) DO

READLINE f INTO currentLine

/* Process currentLine here */

END WHILE

CLOSE f

/* If you need to exit early, remember:

IF someCondition THEN

CLOSE f // always close before RETURN/EXIT

RETURN

END IF

*/

Pseudocode Patterns

1. Reading an Entire File Line‑by‑Line

OPEN "data.txt" FOR READ AS f

WHILE NOT EOF(f) DO

READLINE f INTO currentLine

// e.g. count words, validate format, etc.

END WHILE

CLOSE f

2. Writing Multiple Lines to a New File

OPEN "output.txt" FOR WRITE AS f

FOR i FROM 1 TO n DO

line ← "Record " & i

WRITELINE f, line

END FOR

CLOSE f

3. Appending a Line to an Existing File (Log File)

OPEN "log.txt" FOR APPEND AS f

WRITELINE f, "Program started at " & CURRENTTIME()

CLOSE f

4. Handling Files with an Unknown Number of Lines

lineCount ← 0

OPEN "input.txt" FOR READ AS f

WHILE NOT EOF(f) DO

READLINE f INTO line

lineCount ← lineCount + 1

// Additional processing here

END WHILE

CLOSE f

/* lineCount now holds the total number of lines (L) in the file */

Cross‑Curricular Link (Section 6 – Security & Data Integrity)

  • Validate data immediately after reading (e.g. confirm an integer line really contains an integer).
  • Open a file only in the mode required – this limits accidental overwriting and reduces security risk.
  • Close files promptly to avoid file‑locking and possible data corruption.
  • Use FILEEXISTS before attempting to read a file that may be missing.

Common Errors and How to Avoid Them

  • Forgetting to close a file – always place CLOSE after the last operation, even inside conditional branches or before an early RETURN.
  • Reading past EOF – test EOF(file) before calling READLINE.
  • Mixing read and write modes on the same handle – open separate handles or reopen the file in the required mode.
  • Incorrect newline handlingWRITELINE automatically adds a newline; do not add an extra “\n”.
  • Assuming a fixed number of lines – use the EOF‑controlled loop for files of unknown length.
  • Not checking file existence or permissions – use FILEEXISTS and open only the necessary mode.

Suggested Diagram

Flowchart: OPEN → WHILE NOT EOF → READLINE → Process → (loop) → CLOSE

Practice Exercises

  1. Write pseudocode that reads a text file containing integer values (one per line) and calculates their sum and average.
  2. Extend the code in (1) to also count how many of the integers are even.
  3. Write pseudocode to create a new file that lists each original integer followed by its square, one per line.

Answer Sketch for Exercise 1

sum ← 0

count ← 0

OPEN "numbers.txt" FOR READ AS f

WHILE NOT EOF(f) DO

READLINE f INTO line

value ← STRINGTOINT(line)

sum ← sum + value

count ← count + 1

END WHILE

CLOSE f

IF count > 0 THEN

average ← sum / count

ELSE

average ← 0

END IF

/* sum and average now contain the required results */

Answer Sketch for Exercise 2 (adds even‑count)

sum ← 0

count ← 0

evenCount ← 0

OPEN "numbers.txt" FOR READ AS f

WHILE NOT EOF(f) DO

READLINE f INTO line

value ← STRINGTOINT(line)

sum ← sum + value

count ← count + 1

IF value MOD 2 = 0 THEN

evenCount ← evenCount + 1

END IF

END WHILE

CLOSE f

IF count > 0 THEN

average ← sum / count

ELSE

average ← 0

END IF

/* sum, average and evenCount now hold the results */

Answer Sketch for Exercise 3 (write original and square)

OPEN "numbers.txt" FOR READ AS inFile

OPEN "squares.txt" FOR WRITE AS outFile

WHILE NOT EOF(inFile) DO

READLINE inFile INTO line

value ← STRINGTOINT(line)

square ← value * value

WRITELINE outFile, line & " " & STRING(square)

END WHILE

CLOSE inFile

CLOSE outFile