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
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 data from file
Write data to file (overwrites)
Add data to end of file
Real-Life Example: School Gradebook System
Imagine a teacher's gradebook system that stores student grades:
• 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 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
1. Why do computer programs need to use files? [2 marks]
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
2. What are the three main components of a text file? [3 marks]
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
3. What is the purpose of a filename? [1 mark]
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
4. What happens to data in RAM when a computer is switched off? [1 mark]
Answer
- [1 mark] It is lost/erased
- [Additional] RAM is volatile memory that requires power to maintain data
5. What is the key difference between WRITE and APPEND modes? [2 marks]
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:
- <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
CLOSEFILE Command
When finished with a file, always close it:
- 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
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:
- <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
WRITEFILE Command
Writes one line to a file opened in WRITE or APPEND mode:
- <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
| 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:
- What is the content of "data.txt" after line 4?
- What is the content of "data.txt" after line 7?
- What will be output by the WHILE loop (lines 10-13)?
- How many times will the WHILE loop execute?
Solution:
1. After line 4 (WRITE mode then close):
WRITE mode creates/overwrites file with two lines
2. After line 7 (APPEND mode then close):
APPEND mode adds "Line 3" to the end, preserving existing lines
3. Output from WHILE loop:
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:
Returns BOOLEAN: TRUE if at end of file, FALSE if more data exists
Common Usage:
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:
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: output.txt
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
1. Write the pseudocode command to open a file called "scores.txt" for reading. [1 mark]
Answer
- [1 mark] OPENFILE "scores.txt" FOR READ
- [Additional] The filename must be in quotes if it's a string literal
2. What is the purpose of the CLOSEFILE command? [2 marks]
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
3. Explain what the EOF() function returns and when. [2 marks]
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
4. What data type must the variable be in READFILE command? [1 mark]
Answer
- [1 mark] STRING
- [Additional] Text files contain text (strings), so the variable must be able to store text
5. What happens if you try to READFILE from a file opened in WRITE mode? [2 marks]
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 |
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 |
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 |
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:
- Creates a new file "temperatures.txt"
- Asks the user to enter 5 temperature readings (prompt for each one)
- Writes each temperature to the file on a separate line
- Closes the file
- Reopens the file for reading
- Reads all temperatures and calculates the average
- Outputs the average temperature
- Closes the file
Hint: You'll need a FOR loop for input, WRITEFILE to save, then WHILE NOT EOF() to read back.
Solution:
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:
- Open file in APPEND mode
- Prompt and Input a student name and mark
- If mark greater than or equal to 20 jump to step 5
- Write only the name to the file
- 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:
- 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:
- 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:
- 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:
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:
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
1. When should you use APPEND mode instead of WRITE mode? [2 marks]
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
2. Why is it important to check EOF() immediately after opening a file in READ mode? [2 marks]
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
3. In the LastLines() procedure example, why are three variables (LineX, LineY, LineZ) needed? [2 marks]
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
4. What is the purpose of the REPEAT loop in the complete write/read example? [1 mark]
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
5. In the LogEvents procedure, why is a FOR loop used instead of WHILE NOT EOF? [2 marks]
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
1. Explain why computer programs need to use files rather than just storing data in variables. [3 marks]
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
2. Describe the differences between READ, WRITE, and APPEND file modes. [6 marks]
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.
3. Write pseudocode to read all lines from a file called "data.txt" and output each line with a line number. [5 marks]
Marking Scheme & Answer
- [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.
4. A program needs to log error messages to a file. Explain whether WRITE or APPEND mode should be used and why. [3 marks]
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
5. Write pseudocode for a procedure that takes a filename as parameter and returns the number of lines in that file. [6 marks]
Marking Scheme & Answer
- [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
6. What will happen if you try to READFILE from a file that was opened in WRITE mode? [2 marks]
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
7. Write pseudocode to copy all lines from "source.txt" to "destination.txt". [5 marks]
Marking Scheme & Answer
- [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
8. Explain what the EOF() function tests for and what values it returns. [3 marks]
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
9. Why is it important to always close files after using them? [2 marks]
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
10. Write pseudocode that asks user for their name and age, then saves this information to a file called "userdata.txt". The program should then read back and display all data from the file. [8 marks]
Marking Scheme & Answer
- [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