TF

10.3 Text File Handling

Understanding file operations, reading, writing, and appending text files using pseudocode

Learning Objectives

By the end of this lesson, you will be able to:

  • Show understanding of why files are needed for permanent data storage
  • Write pseudocode to handle text files that consist of one or more lines
  • Use OPENFILE, READFILE, WRITEFILE, and CLOSEFILE commands correctly
  • Understand and use the EOF() function to test for end of file
  • Differentiate between READ, WRITE, and APPEND file modes
  • Implement file operations in pseudocode for various scenarios
  • Process text files line by line using loops

Key Terms

Text File

A file consisting of a sequence of characters formatted into lines, terminated by end-of-line and end-of-file markers

Filename

The unique identifier for a file used by the operating system

OPENFILE

Pseudocode command to open a file before reading from or writing to it

READ Mode

File mode for reading data from a file

WRITE Mode

File mode for writing data to a file; overwrites existing data

APPEND Mode

File mode for adding data to the end of an existing file

READFILE

Pseudocode command to read a line of text from a file

WRITEFILE

Pseudocode command to write a line of text to a file

EOF() Function

Function that returns TRUE if end of file has been reached, FALSE otherwise

CLOSEFILE

Pseudocode command to close a file after use

Permanent Storage

Data storage that persists after the computer is switched off

End-of-File Marker

A special marker at the end of a text file that indicates no more data

Introduction to File Handling

Data needs to be stored permanently. One approach is to use a file. Computer programs store data that will be required again in a file. Every file is identified by its filename.

What is a Text File?

A text file consists of:

  • A sequence of characters formatted into lines
  • Each line is terminated by an end-of-line marker
  • The entire file is terminated by an end-of-file marker
  • Can be opened and edited with simple text editors
Text File Structure
1
This is line one of the text file
2
This is line two
3
This is the last line
End of File Marker (EOF)

Why Use Files?

Permanent Storage

Data in RAM is lost when computer is turned off. Files store data permanently on hard drives or SSDs.

Data Reusability

Programs can save data to files and read it back later, even after restarting the program or computer.

Large Data Sets

Files can store much more data than can fit in RAM at once.

Data Sharing

Files can be shared between different programs or even different computers.

READ

Read data from file

WRITE

Write data to file (overwrites)

APPEND

Add data to end of file

Real-Life Example: School Gradebook System

Imagine a teacher's gradebook system that stores student grades:

grades.txt
1
Alice,85,92,78
2
Bob,72,88,91
3
Charlie,95,87,82
EOF

• The teacher runs the gradebook program each day

• Program reads existing grades from "grades.txt"

• Teacher adds new grades during class

• Program writes updated grades back to the file

• Data persists even if computer is turned off overnight

• Next day, all grades are still there when program restarts

Without files, the teacher would need to re-enter all grades every time the program runs!

File Operations Simulation

See how different file modes affect the contents of a text file. Try reading, writing, and appending to understand the differences.

Current File: sample.txt
File size: 0 lines
File Operations

Current operation: Select a file mode and click "Execute Operation" to see how it works.

How file modes work:

  • READ: Only allows viewing file contents. Cannot modify the file.
  • WRITE: Creates a new file or overwrites existing file completely. All previous data is lost.
  • APPEND: Opens existing file and adds new data to the end. Previous data is preserved.
  • Always use CLOSEFILE when done to ensure data is saved properly.

Check Your Understanding: File Basics

Answer
  • [1 mark] To store data permanently (data persists after computer is switched off)
  • [1 mark] To allow data to be reused when program is run again
  • [Additional] Files can store more data than RAM and allow data sharing between programs
Answer
  • [1 mark] Sequence of characters formatted into lines
  • [1 mark] End-of-line marker after each line
  • [1 mark] End-of-file marker at the end of the file
  • [Additional] Every file has a unique filename to identify it
Answer
  • [1 mark] To uniquely identify a file used by the operating system
  • [Additional] The filename allows programs to locate and access the correct file
Answer
  • [1 mark] It is lost/erased
  • [Additional] RAM is volatile memory that requires power to maintain data
Answer
  • [1 mark] WRITE mode overwrites/deletes all existing data in the file
  • [1 mark] APPEND mode adds new data to the end while preserving existing data
  • [Additional] Use WRITE to create a new file or completely replace contents; use APPEND to add to existing data

File Operations in Pseudocode

To work with files in pseudocode, we use specific commands: OPENFILE, READFILE, WRITEFILE, and CLOSEFILE. Understanding these commands is essential for file handling.

Opening and Closing Files

OPENFILE Command

Before reading from or writing to a file, you must open it:

OPENFILE <file identifier> FOR <file mode>
  • <file identifier>: The filename or variable containing filename
  • <file mode>: READ, WRITE, or APPEND
  • Must be done before any file operations
  • If file doesn't exist in READ mode, an error occurs
  • WRITE mode creates file if it doesn't exist
Examples:
OPENFILE "data.txt" FOR READ
OPENFILE MyFile FOR WRITE
OPENFILE Report FOR APPEND

CLOSEFILE Command

When finished with a file, always close it:

CLOSEFILE <file identifier>
  • Releases the file for use by other programs
  • Ensures all data is properly saved (especially important for WRITE/APPEND)
  • Required for proper file management
  • Use the same file identifier used in OPENFILE
Important:

Forgetting to close files can cause:

  • Data loss (not saved properly)
  • File locking (other programs can't access it)
  • Memory leaks in some systems

Reading and Writing Data

READFILE Command

Reads one line from a file opened in READ mode:

READFILE <file identifier>, <variable>
  • <variable>: Must be STRING data type
  • Reads one line at a time
  • Each call reads the next line
  • File must be opened in READ mode first
  • Use EOF() to check for end of file
Example:
DECLARE LineData : STRING
OPENFILE "notes.txt" FOR READ
READFILE "notes.txt", LineData
OUTPUT LineData // Outputs first line
READFILE "notes.txt", LineData
OUTPUT LineData // Outputs second line

WRITEFILE Command

Writes one line to a file opened in WRITE or APPEND mode:

WRITEFILE <file identifier>, <stringValue>
  • <stringValue>: Can be a string literal or STRING variable
  • Writes one line at a time
  • Adds end-of-line marker after each write
  • File must be opened in WRITE or APPEND mode
  • In WRITE mode, first write erases previous content
Example:
DECLARE StudentName : STRING
StudentName ← "Alice"
OPENFILE "students.txt" FOR WRITE
WRITEFILE "students.txt", StudentName
WRITEFILE "students.txt", "Bob"
CLOSEFILE "students.txt"
Operation Syntax Purpose Valid Modes
OPENFILE OPENFILE <file> FOR <mode> Open a file for reading or writing READ, WRITE, APPEND
READFILE READFILE <file>, <variable> Read one line from file into variable READ only
WRITEFILE WRITEFILE <file>, <value> Write one line to file WRITE, APPEND
CLOSEFILE CLOSEFILE <file> Close the file after use READ, WRITE, APPEND
EOF() EOF(<file>) Check if end of file reached READ only

Activity 1: Trace File Operations

Given the following pseudocode, trace what happens to the file "data.txt" at each step:

1. OPENFILE "data.txt" FOR WRITE
2. WRITEFILE "data.txt", "Line 1"
3. WRITEFILE "data.txt", "Line 2"
4. CLOSEFILE "data.txt"
5. OPENFILE "data.txt" FOR APPEND
6. WRITEFILE "data.txt", "Line 3"
7. CLOSEFILE "data.txt"
8. OPENFILE "data.txt" FOR READ
9. DECLARE TextLine : STRING
10. WHILE NOT EOF("data.txt")
11.     READFILE "data.txt", TextLine
12.     OUTPUT TextLine
13. ENDWHILE
14. CLOSEFILE "data.txt"
  1. What is the content of "data.txt" after line 4?
  2. What is the content of "data.txt" after line 7?
  3. What will be output by the WHILE loop (lines 10-13)?
  4. How many times will the WHILE loop execute?
Solution:

1. After line 4 (WRITE mode then close):

1
Line 1
2
Line 2
EOF

WRITE mode creates/overwrites file with two lines

2. After line 7 (APPEND mode then close):

1
Line 1
2
Line 2
3
Line 3
EOF

APPEND mode adds "Line 3" to the end, preserving existing lines

3. Output from WHILE loop:

Line 1
Line 2
Line 3

The loop reads and outputs each line until EOF

4. Number of loop executions:

3 times (once for each line in the file)

WHILE NOT EOF continues until end of file is reached

The EOF() Function

The EOF() function is used to test for the end of a file. It returns TRUE if the end of file has been reached and FALSE otherwise.

Syntax:
EOF(<file identifier>)

Returns BOOLEAN: TRUE if at end of file, FALSE if more data exists

Common Usage:
WHILE NOT EOF(MyFile)
    READFILE MyFile, DataLine
    // Process DataLine
ENDWHILE

Read all lines until end of file is reached

Important Notes about EOF()
  • EOF() only works with files opened in READ mode
  • Every time EOF() is called, it tests for the end-of-file marker
  • Use WHILE NOT EOF() to read entire files
  • If file might be empty, check EOF() immediately after OPENFILE
  • After EOF() returns TRUE, any further READFILE will cause an error

Real-Life Example: Online Shopping Cart

An online store saves customer shopping carts to files:

// When customer adds item to cart:
OPENFILE "cart_123.txt" FOR APPEND
WRITEFILE "cart_123.txt", "iPhone,999.99"
CLOSEFILE "cart_123.txt"
// When customer returns to site:
OPENFILE "cart_123.txt" FOR READ
WHILE NOT EOF("cart_123.txt")
READFILE "cart_123.txt", ItemData
// Display item in cart
ENDWHILE
CLOSEFILE "cart_123.txt"

The customer can close their browser, turn off their computer, and return days later - their cart items are still saved because they were stored in a file, not just in RAM.

Pseudocode Execution Simulator

Step through pseudocode execution to see how file operations work. Watch how the file contents change with each command.

Pseudocode Editor
File Operations Program
Current line: 1
File: output.txt
Mode: CLOSED | Lines: 0
Output Console

How to use: Click "Execute Next Line" to step through the pseudocode. Watch how the file contents change with WRITE and APPEND operations, and how READ operations read data from the file.

Check Your Understanding: File Operations

Answer
  • [1 mark] OPENFILE "scores.txt" FOR READ
  • [Additional] The filename must be in quotes if it's a string literal
Answer
  • [1 mark] To release the file for use by other programs
  • [1 mark] To ensure all data is properly saved to the file
  • [Additional] Important for data integrity and system resource management
Answer
  • [1 mark] Returns TRUE when the end of the file has been reached
  • [1 mark] Returns FALSE when there is still more data to read
  • [Additional] Used in loops to read all data from a file without errors
Answer
  • [1 mark] STRING
  • [Additional] Text files contain text (strings), so the variable must be able to store text
Answer
  • [1 mark] An error will occur
  • [1 mark] READFILE can only be used with files opened in READ mode
  • [Additional] Each file mode has specific allowed operations: READ for reading, WRITE/APPEND for writing

Practical Examples and Exam Questions

Now let's look at practical examples and exam-style questions to understand how file handling is tested in the Cambridge 9618 exams.

Writing to a Text File

Basic Write Example

The following pseudocode statements provide facilities for writing to a file:

Command Example Comment
OPENFILE OPENFILE <filename> FOR WRITE // open the file for writing
WRITEFILE WRITEFILE <filename>, <stringValue> // write a line of text to the file
CLOSEFILE CLOSEFILE <filename> // close file
Complete Example:
OPENFILE "output.txt" FOR WRITE
WRITEFILE "output.txt", "Hello, World!"
WRITEFILE "output.txt", "This is line 2"
CLOSEFILE "output.txt"

Creates a file "output.txt" with two lines. If file already exists, it is completely overwritten.

Reading from a Text File

Basic Read Example

An existing file can be read by a program:

Command Example Comment
OPENFILE OPENFILE <filename> FOR READ // open file for reading
READFILE READFILE <filename>, <stringVariable> // read a line of text from the file
CLOSEFILE CLOSEFILE <filename> // close file
Complete Example:
DECLARE LineData : STRING
OPENFILE "input.txt" FOR READ
READFILE "input.txt", LineData // Reads first line
OUTPUT LineData
READFILE "input.txt", LineData // Reads second line
OUTPUT LineData
CLOSEFILE "input.txt"

Reads and outputs the first two lines from "input.txt". Use a loop with EOF() to read all lines.

Appending to a Text File

Append Mode Example

Sometimes we may wish to add data to an existing file rather than create a new file. This can be done in Append mode. It adds new data to end of existing file.

Command Example Comment
OPENFILE OPENFILE <filename> FOR APPEND // open file for append
WRITEFILE WRITEFILE <filename>, <stringValue> // write a line of text to the file
CLOSEFILE CLOSEFILE <filename> // close file
Complete Example:
// File "log.txt" already contains some data
OPENFILE "log.txt" FOR APPEND
WRITEFILE "log.txt", "New log entry: User logged in"
WRITEFILE "log.txt", "Timestamp: 2023-10-15 14:30"
CLOSEFILE "log.txt"

Adds two new lines to the end of "log.txt" without affecting existing content. Use APPEND when you want to add to a file, not replace it.

Activity 2: Complete File Handling Program

Write pseudocode for a program that:

  1. Creates a new file "temperatures.txt"
  2. Asks the user to enter 5 temperature readings (prompt for each one)
  3. Writes each temperature to the file on a separate line
  4. Closes the file
  5. Reopens the file for reading
  6. Reads all temperatures and calculates the average
  7. Outputs the average temperature
  8. Closes the file

Hint: You'll need a FOR loop for input, WRITEFILE to save, then WHILE NOT EOF() to read back.

Solution:
DECLARE Temp, TempString, Total : INTEGER
DECLARE Count, Average : INTEGER
DECLARE FileData : STRING
// Part 1: Write temperatures to file
OPENFILE "temperatures.txt" FOR WRITE
FOR Count ← 1 TO 5
    OUTPUT "Enter temperature ", Count, ":"
    INPUT Temp
    WRITEFILE "temperatures.txt", STR(Temp)
NEXT Count
CLOSEFILE "temperatures.txt"
// Part 2: Read back and calculate average
Total ← 0
Count ← 0
OPENFILE "temperatures.txt" FOR READ
WHILE NOT EOF("temperatures.txt")
    READFILE "temperatures.txt", FileData
    Temp ← VAL(FileData)
    Total ← Total + Temp
    Count ← Count + 1
ENDWHILE
CLOSEFILE "temperatures.txt"
// Calculate and output average
IF Count > 0 THEN
    Average ← Total / Count
    OUTPUT "Average temperature: ", Average
ELSE
    OUTPUT "No temperatures found"
ENDIF

Key Points:

  • Use WRITE mode to create/overwrite the file initially
  • Convert integer temperature to string using STR() before writing
  • Use WHILE NOT EOF() to read all lines (not just 5, in case file is modified)
  • Convert string back to integer using VAL() when reading
  • Always close the file after each operation
  • Check for division by zero (Count > 0)

Exam Style Questions

ESQ 1: Student Support List

Algorithm will process data from a test taken by a group of students. Algorithm will prompt and input name and test mark for 35 students. Algorithm will add names of all students with test mark of less than 20 to existing text file Support_List.txt which already contains data from other group tests.

(i) Describe steps that algorithm should perform. Do not include pseudocode in your answer. [5]
Answer:
  1. Open file in APPEND mode
  2. Prompt and Input a student name and mark
  3. If mark greater than or equal to 20 jump to step 5
  4. Write only the name to the file
  5. Repeat from Step 2 for 35 times
(ii) Explain why it is better to store names of students in a file rather than in array. [2]
Answer:

Data in a file is saved after computer is switched off and stored permanently. No need to re-enter data when program is re-run.

(iii) Explain why WRITE mode cannot be used in the answer to part (a)(i) [1]
Answer:

So that existing file data is not overwritten.

ESQ 2: LogEvents Procedure

LogArray is 1D array containing 500 elements of type STRING. A procedure, LogEvents, is required to add data from array to end of existing file LoginFile.txt. Unused array elements are assigned value "Empty". These can occur anywhere in array and should not added to file. Write pseudocode for procedure LogEvents.

Solution:
PROCEDURE LogEvents ( )
    DECLARE FileData : STRING
    DECLARE ArrayIndex : INTEGER
    OPENFILE "LoginFile.txt" FOR APPEND
    FOR ArrayIndex ← 1 TO 500
        IF LogArray[ArrayIndex] <> "Empty" THEN
            FileData ← LogArray[ArrayIndex]
            WRITEFILE "LoginFile.txt", FileData
        ENDIF
    NEXT
    CLOSEFILE "LoginFile.txt"
ENDPROCEDURE
  • Uses APPEND mode to add to existing file
  • Loops through all 500 array elements
  • Checks if element is not "Empty" before writing
  • Correctly closes the file after writing

ESQ 3: Preview Procedure

A procedure Preview() will:

  • take name of a text file as a parameter
  • output a warning message if file is empty
  • otherwise output first five lines from file (or as many lines as there are in file if this number is less than five)
Solution:
PROCEDURE Preview (ThisFile : STRING)
    DECLARE LineNum : INTEGER
    DECLARE ThisLine : STRING
    OPENFILE ThisFile FOR READ
    IF EOF(ThisFile) THEN
        OUTPUT "Warning Message"
    ELSE
        LineNum ← 1
        WHILE LineNum < 6 AND NOT EOF(ThisFile)
            READFILE Thisfile, ThisLine
            OUTPUT ThisLine
            LineNum ← LineNum + 1
        ENDWHILE
    ENDIF
    CLOSEFILE ThisFile
ENDPROCEDURE
  • Takes filename as parameter (ThisFile : STRING)
  • Checks EOF immediately after opening to detect empty file
  • Uses WHILE LineNum < 6 AND NOT EOF(ThisFile) to read up to 5 lines or until EOF
  • Correctly closes file in both branches

ESQ 4: LastLines Procedure

A procedure LastLines() will:

  • take name of a text file as a parameter
  • output last three lines from that file, in same order as they appear in file
  • Use local variables LineX, LineY and LineZ to store the three lines from file
  • You may assume file exists and contains at least three lines
Solution:
PROCEDURE LastLines(ThisFile : STRING)
    DECLARE ThisLine, LineX, LineY, LineZ : STRING
    OPENFILE ThisFile FOR READ
    LineY ← ""
    LineZ ← ""
    WHILE NOT EOF(ThisFile)
        READFILE ThisFile, ThisLine // read a line
        LineX ← LineY
        LineY ← LineZ
        LineZ ← ThisLine
    ENDWHILE
    CLOSEFILE ThisFile
    OUTPUT LineX
    OUTPUT LineY
    OUTPUT LineZ
ENDPROCEDURE
  • Uses three variables to "shift" lines through as reading
  • After reading all lines, LineX, LineY, LineZ contain the last three lines
  • Reads entire file with WHILE NOT EOF
  • Outputs the three lines in correct order (X, Y, Z)

Real-Life Example: Chat Application

A simple chat application uses file handling to save conversation history:

// When user sends a message:
OPENFILE "chat_history.txt" FOR APPEND
WRITEFILE "chat_history.txt", "User123: Hello everyone!"
WRITEFILE "chat_history.txt", "Timestamp: 14:30"
CLOSEFILE "chat_history.txt"
// When loading chat history:
OPENFILE "chat_history.txt" FOR READ
IF EOF("chat_history.txt") THEN
OUTPUT "No chat history"
ELSE
WHILE NOT EOF("chat_history.txt")
READFILE "chat_history.txt", ChatLine
// Display ChatLine in chat window
ENDWHILE
ENDIF
CLOSEFILE "chat_history.txt"

The chat history is preserved even if the application is closed and reopened later. New messages are appended to the end of the file without deleting old messages.

Complete Example: Write and Read File

This pseudocode shows how file myText.txt could be written to and read from:

DECLARE textLine : STRING
DECLARE myFile : STRING
myFile ← "myText.txt"
OPENFILE myFile FOR WRITE
REPEAT
    OUTPUT "Enter Line of Text"
    INPUT textLine
    IF textLine <> " " THEN
        WRITEFILE myFile, textLine
    ELSE
        CLOSEFILE(myFile)
    ENDIF
UNTIL textLine = " "
OUTPUT "The file contains these lines of text "
OPENFILE myFile FOR READ
REPEAT
    READFILE myFile, textLine
    OUTPUT textLine
UNTIL EOF( myFile)
CLOSEFILE (myFile)
Key Points from this Example
  • Uses a variable (myFile) to store filename instead of repeating string literal
  • REPEAT loop continues until user enters a space (sentinel value)
  • Closes file when user enters space (inside IF statement)
  • REPEAT UNTIL EOF() reads entire file
  • Note: Should use WHILE NOT EOF() instead of REPEAT UNTIL EOF() to avoid reading past end of file if empty

Check Your Understanding: Practical Applications

Answer
  • [1 mark] When you want to add new data to an existing file
  • [1 mark] When you don't want to overwrite or lose the existing data in the file
  • [Additional] Examples: adding to a log file, appending new records to a database file, adding new messages to a chat history
Answer
  • [1 mark] To detect if the file is empty (contains no data)
  • [1 mark] To avoid trying to READFILE from an empty file, which could cause an error
  • [Additional] This allows the program to handle empty files gracefully with appropriate messages
Answer
  • [1 mark] To store the last three lines as we read through the file
  • [1 mark] They act as a "shifting window" - each new line pushes the oldest line out
  • [Additional] After reading entire file, these variables contain exactly the last three lines in correct order
Answer
  • [1 mark] To repeatedly ask for and write lines of text until user enters a space (sentinel value)
  • [Additional] Allows user to enter multiple lines without knowing in advance how many there will be
Answer
  • [1 mark] Because we're reading from an array, not a file
  • [1 mark] We know exactly how many elements (500) are in the array
  • [Additional] FOR loops are used when you know how many iterations are needed; WHILE NOT EOF is for reading unknown amounts of data from files

Key Takeaways

  • Files are needed for permanent storage of data that persists after computer is switched off
  • A text file consists of characters formatted into lines with end-of-line and end-of-file markers
  • Use OPENFILE <filename> FOR <mode> to open a file (modes: READ, WRITE, APPEND)
  • READ mode allows reading from file; WRITE mode overwrites file; APPEND mode adds to end of file
  • Use READFILE <filename>, <variable> to read one line into a STRING variable
  • Use WRITEFILE <filename>, <stringValue> to write one line to a file
  • Always use CLOSEFILE <filename> when finished with a file
  • The EOF() function returns TRUE when end of file is reached, FALSE otherwise
  • Use WHILE NOT EOF(filename) to read all lines from a file
  • Check EOF() immediately after opening to detect empty files
  • Files allow data to be reused when program is run again - no need to re-enter data
  • Use APPEND when adding to existing data; use WRITE when creating new file or replacing all data
  • Text files store everything as strings - use STR() to convert to string and VAL() to convert back
  • File handling is essential for programs that need to save data between runs (e.g., settings, user data, logs)

Question Bank

Marking Scheme & Answer
  • [1 mark] Data in variables is stored in RAM which is volatile (lost when power is off)
  • [1 mark] Files provide permanent storage on hard drive/SSD that persists after computer is switched off
  • [1 mark] Files allow data to be reused when program is run again without needing to re-enter it
  • [Additional] Files can store much larger amounts of data than typically available in RAM
Marking Scheme & Answer
Mode Purpose Effect on Existing Data Allowed Operations
READ Read data from file No change to file READFILE only
WRITE Write data to file Overwrites/deletes all existing data WRITEFILE only
APPEND Add data to file Preserves existing data, adds to end WRITEFILE only

Key points: READ is for input, WRITE/APPEND are for output. WRITE starts fresh, APPEND adds to existing. Use WRITE for new files or to replace everything; use APPEND to add to log files, databases, etc.

Marking Scheme & Answer
DECLARE LineData : STRING
DECLARE LineNumber : INTEGER
LineNumber ← 1
OPENFILE "data.txt" FOR READ
WHILE NOT EOF("data.txt")
    READFILE "data.txt", LineData
    OUTPUT LineNumber, ": ", LineData
    LineNumber ← LineNumber + 1
ENDWHILE
CLOSEFILE "data.txt"
  • [1 mark] Correct variable declarations
  • [1 mark] Opens file in READ mode
  • [2 marks] Correct WHILE NOT EOF loop structure
  • [1 mark] Correctly closes file
  • [Additional] LineNumber variable increments correctly to show 1:, 2:, 3:, etc.
Marking Scheme & Answer
  • [1 mark] APPEND mode should be used
  • [1 mark] Because error logs need to accumulate over time
  • [1 mark] WRITE mode would overwrite previous errors each time, losing the log history
  • [Additional] Log files should preserve all entries for debugging and analysis; APPEND adds new errors to the end while keeping old ones
Marking Scheme & Answer
FUNCTION LineCount(ThisFile : STRING) RETURNS INTEGER
    DECLARE CurrentLine : STRING
    DECLARE Count : INTEGER
    Count ← 0
    OPENFILE ThisFile FOR READ
    WHILE NOT EOF(ThisFile)
        READFILE ThisFile, CurrentLine
        Count ← Count + 1
    ENDWHILE
    CLOSEFILE ThisFile
    RETURN Count
ENDFUNCTION
  • [1 mark] Correct FUNCTION definition with parameter and return type
  • [1 mark] Correct variable declarations
  • [1 mark] Initializes Count to 0
  • [1 mark] Opens file in READ mode
  • [1 mark] Correct WHILE NOT EOF loop to read all lines
  • [1 mark] Correctly closes file and returns count
  • [Additional] Count increments for each line read; function returns total
Marking Scheme & Answer
  • [1 mark] An error will occur
  • [1 mark] READFILE can only be used with files opened in READ mode
  • [Additional] Each file mode has specific allowed operations: READ mode allows READFILE; WRITE and APPEND modes allow WRITEFILE
Marking Scheme & Answer
DECLARE LineData : STRING
OPENFILE "source.txt" FOR READ
OPENFILE "destination.txt" FOR WRITE
WHILE NOT EOF("source.txt")
    READFILE "source.txt", LineData
    WRITEFILE "destination.txt", LineData
ENDWHILE
CLOSEFILE "source.txt"
CLOSEFILE "destination.txt"
  • [1 mark] Opens source file in READ mode
  • [1 mark] Opens destination file in WRITE mode (overwrites any existing content)
  • [2 marks] Correct WHILE NOT EOF loop to read all lines and write them
  • [1 mark] Correctly closes both files
  • [Additional] If you want to append instead of overwrite, use APPEND mode for destination
Marking Scheme & Answer
  • [1 mark] Tests for the end-of-file marker in a text file
  • [1 mark] Returns TRUE if end of file has been reached
  • [1 mark] Returns FALSE if there is still more data to read
  • [Additional] Used with files opened in READ mode to determine when to stop reading
Marking Scheme & Answer
  • [1 mark] To ensure all data is properly saved to the file (especially for WRITE/APPEND)
  • [1 mark] To release the file for use by other programs (file locking)
  • [Additional] Prevents data corruption and memory/resource leaks in some systems
Marking Scheme & Answer
DECLARE UserName, FileLine : STRING
DECLARE UserAge : INTEGER
// Get user input
OUTPUT "Enter your name: "
INPUT UserName
OUTPUT "Enter your age: "
INPUT UserAge
// Write to file (APPEND to keep previous entries)
OPENFILE "userdata.txt" FOR APPEND
WRITEFILE "userdata.txt", "Name: " + UserName
WRITEFILE "userdata.txt", "Age: " + STR(UserAge)
CLOSEFILE "userdata.txt"
// Read back and display all data
OUTPUT "All user data:"
OPENFILE "userdata.txt" FOR READ
WHILE NOT EOF("userdata.txt")
    READFILE "userdata.txt", FileLine
    OUTPUT FileLine
ENDWHILE
CLOSEFILE "userdata.txt"
  • [1 mark] Correct variable declarations
  • [1 mark] Gets user input for name and age
  • [1 mark] Opens file in APPEND mode (to keep previous entries)
  • [1 mark] Writes both pieces of data to file (converts age to string)
  • [1 mark] Closes file after writing
  • [1 mark] Opens file in READ mode
  • [1 mark] Correct WHILE NOT EOF loop to read all data
  • [1 mark] Closes file after reading
  • [Additional] Uses APPEND so multiple runs add data; uses STR() to convert integer to string