Write pseudocode to handle text files that consist of one or more lines
Understand how to open, read, write, and close files
Use EOF (End of File) function to process files
Differentiate between READ, WRITE, and APPEND modes
Write programs that combine file handling with loops and conditions
📋 Prior Knowledge Required
Understanding of variables and data types (especially STRING)
Knowledge of loops (WHILE, REPEAT...UNTIL, FOR)
Understanding of conditional statements (IF...THEN...ELSE)
Basic knowledge of arrays (1D arrays)
Understanding of procedures and functions
🌟 Did You Know?
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. Without files, all data would be lost when a program ends or the computer is turned off!
1. Why Files Are Needed
Computer programs store data that will be required again in a file. Every file is identified by its filename. Text files contain a sequence of characters formatted into lines.
📖 Key Concepts
Each line in a text file is terminated by an end-of-line marker
Text file is terminated by an end-of-file marker
Files allow data to be stored permanently on storage devices
Data in files persists even after the program ends or computer is turned off
Data Storage
Lifetime
Example
Variables in Memory
Temporary (lost when program ends)
Local variables, arrays
Files on Disk
Permanent (saved after program ends)
Text files (.txt)
⚠️ Important: Why Use Files Instead of Arrays?
When asked why it is better to store data in a file rather than in an array:
Data in a file is saved after the computer is switched off
Data is stored permanently
No need to re-enter data when the program is re-run
2. Basic File Operations
2.1 Opening a File
Before performing any operation, you must open the file. The file must be opened in the correct mode for the operation you want to perform.
OPENFILE <FileName> FOR <Mode>
📖 File Modes Explained
READ Mode: Opens the file to read its content. Data can only be read, not modified.
WRITE Mode: Opens the file to create a new file or overwrite an existing file. Any existing data will be lost.
APPEND Mode: Opens the file to add data to the end. Existing data is preserved.
Mode
Purpose
Existing Data
READ
Read data from file
Preserved ✓
WRITE
Create new or overwrite file
Overwritten ✗
APPEND
Add data to end of file
Preserved ✓
2.2 Closing a File
Once you finish your operations, always close the file to free up resources and ensure data is properly saved.
CLOSEFILE <FileName>
💡 Exam Tip
Always close files after operations! Forgetting to close a file is a common mistake. In exams, marks are often allocated for closing files properly.
3. Reading from Files
3.1 The READFILE Command
Once the file is opened in READ mode, it can be read from a line at a time.
READFILE <FileName>, <Variable>
⚠️ Important
The variable must be of data type STRING. Each READFILE command reads one line from the file.
This opens the file, reads the first line into the variable StudentName, outputs it, and closes the file.
3.3 The EOF Function
EOF stands for End of File. It is used to check whether the program has reached the end of a file when reading its contents.
📖 EOF Function Syntax
EOF(<FileName>)
Returns TRUE if the end of the file has been reached
Returns FALSE if there is more data to read
3.4 Using EOF with WHILE Loop
To read a file from beginning to end, use a loop that continues while NOT EOF:
OPENFILE "StudentData.txt" FOR READ
DECLARE StudentName : STRING
WHILE NOT EOF("StudentData.txt")
READFILE "StudentData.txt", StudentName
OUTPUT StudentName
ENDWHILE
CLOSEFILE "StudentData.txt"
💡 Exam Tip
If it is possible that the file contains no data, it is better to use WHILE NOT EOF rather than REPEAT...UNTIL EOF, because WHILE checks the condition before reading.
4. Writing to Files
4.1 The WRITEFILE Command
To save new information in a file, use the WRITEFILE operation. The file must be opened in WRITE or APPEND mode.
WRITEFILE <FileName>, <Data>
📖 Key Points
Each WRITEFILE command writes one line to the file
The data must be of type STRING
In WRITE mode, existing data is overwritten
In APPEND mode, data is added to the end of the file
4.2 Example: Writing to a New File
// Step 1: Open the file for writing
OPENFILE "StudentData.txt" FOR WRITE
// Step 2: Write names into the file
WRITEFILE "StudentData.txt", "Alice"
WRITEFILE "StudentData.txt", "Bob"
WRITEFILE "StudentData.txt", "Charlie"
// Step 3: Close the file
CLOSEFILE "StudentData.txt"
📝 What This Does
Opens "StudentData.txt" in WRITE mode (creates new or overwrites)
Writes three names, each on a separate line
Closes the file to save changes
4.3 Using Variables with WRITEFILE
DECLARE file : STRING
DECLARE name : STRING
file ← "StudentData.txt"
OPENFILE file FOR WRITE
REPEAT
OUTPUT "Enter a name (or blank to finish):"
INPUT name
IF name <> "" THEN
WRITEFILE file, name
ENDIF
UNTIL name = ""
CLOSEFILE file
❌ Common Mistake
Don't forget to close the file! If you don't close the file, data may not be saved properly.
5. Appending to Files
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 the end of the existing file.
📖 When to Use APPEND Mode
When you want to add data to an existing file
When you need to preserve existing data
When the file already contains data from previous operations
5.1 Example: Appending Data
// Open the existing file for appending
OPENFILE "StudentData.txt" FOR APPEND
// Write new names to the end of the file
WRITEFILE "StudentData.txt", "Mansoor"
WRITEFILE "StudentData.txt", "Mehrin"
// Close the file
CLOSEFILE "StudentData.txt"
📝 What This Does
Opens "StudentData.txt" in APPEND mode
Adds two new names to the end of the file
Existing data (Alice, Bob, Charlie) is preserved
⚠️ Important: Why Not Use WRITE Mode?
If you use WRITE mode on an existing file, all previous data will be overwritten and lost. Always use APPEND mode when you want to keep existing data!
💡 Exam Tip - Common Question
Question: "Explain why WRITE mode cannot be used to add data to an existing file."
Answer: So that existing file data is not overwritten. WRITE mode would erase all existing data before writing new data.
6. Complete Example: Write and Read
This example shows how a file could be written to and then read from in the same program.
DECLARE textLine : STRING
DECLARE myFile : STRING
myFile ← "myText.txt"
// ===== WRITING TO FILE =====
OPENFILE myFile FOR WRITE
REPEAT
OUTPUT "Please enter a line of text:"
INPUT textLine
IF textLine <> ""
THEN
WRITEFILE myFile, textLine
ELSE
CLOSEFILE(myFile)
ENDIF
UNTIL textLine = ""
// ===== READING FROM FILE =====
OUTPUT "The file contains these lines of text:"
OPENFILE myFile FOR READ
REPEAT
READFILE myFile, textLine
OUTPUT textLine
UNTIL EOF(myFile)
CLOSEFILE(myFile)
📝 How This Works
Opens file in WRITE mode
Loops to get user input until blank line entered
Writes each non-blank line to file
Closes file when input is complete
Reopens file in READ mode
Reads and outputs each line until EOF
Closes file again
Identifier
Data Type
Description
textLine
STRING
Line of text read from/written to file
myFile
STRING
File name ("myText.txt")
7. Practical Applications
7.1 Counting Items in a File
// Count how many lines are in a file
DECLARE FruitName : STRING
DECLARE FruitCount : INTEGER
FruitCount ← 0
OPENFILE "FruitFile.txt" FOR READ
WHILE NOT EOF("FruitFile.txt")
READFILE "FruitFile.txt", FruitName
FruitCount ← FruitCount + 1
ENDWHILE
CLOSEFILE "FruitFile.txt"
OUTPUT "Total number of fruits: ", FruitCount
7.2 Processing Multiple Fields
Sometimes files contain multiple related pieces of data per record. Each piece is on a separate line.
Example: A staff file where each person has 3 lines: Name, Age, Position. To count CEOs:
DECLARE Name, Position : STRING
DECLARE Age : INTEGER
DECLARE CEOCount : INTEGER
CEOCount ← 0
OPENFILE "staff.txt" FOR READ
WHILE NOT EOF("staff.txt")
READFILE "staff.txt", Name // Line 1: Name
READFILE "staff.txt", Age // Line 2: Age (as string, convert)
READFILE "staff.txt", Position // Line 3: Position
IF Position = "CEO" THEN
CEOCount ← CEOCount + 1
ENDIF
ENDWHILE
CLOSEFILE "staff.txt"
OUTPUT "Number of CEOs: ", CEOCount
💡 Exam Tip - Multi-line Records
When each record spans multiple lines, use multiple READFILE statements inside the loop - one for each field. The order must match how data was written!
8. Files and Arrays
8.1 Reading File Data into an Array
Often we need to read file contents into an array for processing. This combines file handling with array operations.
// Read 25 lines from Data.txt into an array
DECLARE DataArray : ARRAY[1:25] OF INTEGER
DECLARE Counter : INTEGER
Counter ← 0
OPENFILE "Data.txt" FOR READ
WHILE NOT EOF("Data.txt") AND Counter < 25
Counter ← Counter + 1
READFILE "Data.txt", DataArray[Counter]
ENDWHILE
CLOSEFILE "Data.txt"
8.2 Writing Array Data to a File
Conversely, we may need to save array contents to a file for permanent storage.
// Write array contents to a file
DECLARE Names : ARRAY[1:100] OF STRING
DECLARE Index : INTEGER
OPENFILE "Names.txt" FOR WRITE
FOR Index ← 1 TO 100
IF Names[Index] <> "" THEN
WRITEFILE "Names.txt", Names[Index]
ENDIF
NEXT Index
CLOSEFILE "Names.txt"
⚠️ Important: Array vs File
When to use arrays: When you need fast access, sorting, searching, or modifying data during program execution.
When to use files: When you need data to persist between program runs.
8.3 Procedure Example: Writing Array to File
// Procedure to write non-empty array elements to file
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 ArrayIndex
CLOSEFILE "LoginFile.txt"
ENDPROCEDURE
9. Advanced File Procedures
9.1 Procedure with File Parameter
A procedure can take a filename as a parameter, making it reusable for different files.
// Preview first 5 lines of a file
PROCEDURE Preview(FileName : STRING)
DECLARE Line : STRING
DECLARE Count : INTEGER
OPENFILE FileName FOR READ
Count ← 0
WHILE NOT EOF(FileName) AND Count < 5
READFILE FileName, Line
OUTPUT Line
Count ← Count + 1
ENDWHILE
IF Count = 0 THEN
OUTPUT "Warning: File is empty!"
ENDIF
CLOSEFILE FileName
ENDPROCEDURE
// Usage:
// CALL Preview("MyData.txt")
9.2 Reading Last N Lines
To read the last lines from a file, we need to store all lines and then output the last ones.
// Output last 3 lines from file
PROCEDURE LastLines(FileName : STRING)
DECLARE LineX, LineY, LineZ : STRING
DECLARE CurrentLine : STRING
LineX ← ""
LineY ← ""
LineZ ← ""
OPENFILE FileName FOR READ
WHILE NOT EOF(FileName)
// Shift lines: Z gets Y, Y gets X, X gets current
LineZ ← LineY
LineY ← LineX
READFILE FileName, LineX
ENDWHILE
CLOSEFILE FileName
// Output in original order
OUTPUT LineZ
OUTPUT LineY
OUTPUT LineX
ENDPROCEDURE
📝 How the Shifting Works
Three variables store the most recent three lines
Each time a new line is read, old values "shift" down
After EOF, we have the last 3 lines in LineZ, LineY, LineX
Output them in order: LineZ (oldest), LineY, LineX (newest)
10. Exam-Style Questions
1. An algorithm will process data from a test taken by a group of students. The algorithm will prompt and input name and test mark for 35 students. The 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. Describe the steps that the algorithm should perform. Do not include pseudocode. [5 marks]
Answer:
Open file in APPEND mode
Prompt and input a student name and mark
If mark is less than 20, write the name to the file
Repeat steps 2-3 for all 35 students
Close the file after all students processed
Additional points for deeper understanding:
APPEND mode is essential to preserve existing data
Only the name needs to be written, not the mark (as per question)
Could use a FOR loop (1 TO 35) or counter-based REPEAT
2. Explain why it is better to store names of students in a file rather than in an array. [3 marks]
Answer:
Data in a file is saved after the computer is switched off
Data is stored permanently on the storage device
No need to re-enter data when the program is re-run
Additional points:
Arrays are stored in RAM (volatile memory)
Files allow data to persist between program executions
Files can handle larger amounts of data than memory-limited arrays
3. Explain why WRITE mode cannot be used in the answer to question 1 (adding to an existing file). [2 marks]
Answer:
WRITE mode would overwrite existing data in the file
The existing data from other group tests would be lost
Additional explanation:
WRITE mode creates a new file or completely replaces existing content
APPEND mode adds to the end without destroying existing data
This is why choosing the correct file mode is crucial
4. LogArray is a 1D array containing 500 elements of type STRING. A procedure, LogEvents, is required to add data from the array to the end of existing file LoginFile.txt. Unused array elements are assigned value "Empty". These can occur anywhere in the array and should not be added to the file. Write pseudocode for the procedure LogEvents. [6 marks]
Answer:
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 ArrayIndex
CLOSEFILE "LoginFile.txt"
ENDPROCEDURE
Marks allocated for:
Opening file in APPEND mode
Correct loop structure (FOR 1 TO 500)
Correct IF condition checking for "Empty"
Correct WRITEFILE statement
Closing the file
Correct procedure structure
10. Exam-Style Questions (Continued)
5. A procedure Preview() will: take the 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 if less than five). Write pseudocode for the procedure Preview(). [6 marks]
Answer:
PROCEDURE Preview(FileName : STRING)
DECLARE Line : STRING
DECLARE Count : INTEGER
OPENFILE FileName FOR READ
Count ← 0
WHILE NOT EOF(FileName) AND Count < 5
READFILE FileName, Line
OUTPUT Line
Count ← Count + 1
ENDWHILE
IF Count = 0 THEN
OUTPUT "Warning: File is empty!"
ENDIF
CLOSEFILE FileName
ENDPROCEDURE
Key points:
Parameter used correctly for file name
WHILE with both EOF check AND count check
Counter incremented correctly
Empty file check after loop
6. A procedure LastLines() will: take the name of a text file as a parameter, output the last three lines from that file in the same order as they appear in file. Use local variables LineX, LineY and LineZ to store the three lines. Assume the file exists and contains at least three lines. Write pseudocode for procedure LastLines(). [6 marks]
Three variables declared for storing last three lines
Shifting mechanism: Z←Y←X←NewLine
Output in correct order (oldest to newest)
7. Write pseudocode to open a file named "Fruits.txt", count the total number of lines using a WHILE NOT EOF loop, and display the total count before closing the file. [5 marks]
Answer:
DECLARE FruitName : STRING
DECLARE Count : INTEGER
Count ← 0
OPENFILE "Fruits.txt" FOR READ
WHILE NOT EOF("Fruits.txt")
READFILE "Fruits.txt", FruitName
Count ← Count + 1
ENDWHILE
CLOSEFILE "Fruits.txt"
OUTPUT "Total number of fruits: ", Count
Key points:
Counter initialized to 0 before loop
WHILE NOT EOF structure
Counter incremented inside loop
File closed after loop
Output shows total count
8. Write pseudocode to create a new file named "Movies.txt" and store the names of five movies (one per line). Then write code to read and display all movies from the file. [8 marks]
Answer:
// Writing movies to file
OPENFILE "Movies.txt" FOR WRITE
WRITEFILE "Movies.txt", "The Shawshank Redemption"
WRITEFILE "Movies.txt", "The Godfather"
WRITEFILE "Movies.txt", "The Dark Knight"
WRITEFILE "Movies.txt", "Pulp Fiction"
WRITEFILE "Movies.txt", "Forrest Gump"
CLOSEFILE "Movies.txt"
// Reading and displaying movies
DECLARE MovieName : STRING
OPENFILE "Movies.txt" FOR READ
WHILE NOT EOF("Movies.txt")
READFILE "Movies.txt", MovieName
OUTPUT MovieName
ENDWHILE
CLOSEFILE "Movies.txt"
10. Exam-Style Questions (Continued)
9. A text file "staff.txt" contains information about staff members. Each person's data is stored over three lines: Name, Age, Position. Write pseudocode to count how many people have the position "CEO" and how many do not. Output both counts. [7 marks]
Answer:
DECLARE Name, Position : STRING
DECLARE Age : STRING
DECLARE CEOCount, NotCEOCount : INTEGER
CEOCount ← 0
NotCEOCount ← 0
OPENFILE "staff.txt" FOR READ
WHILE NOT EOF("staff.txt")
READFILE "staff.txt", Name
READFILE "staff.txt", Age
READFILE "staff.txt", Position
IF Position = "CEO" THEN
CEOCount ← CEOCount + 1
ELSE
NotCEOCount ← NotCEOCount + 1
ENDIF
ENDWHILE
CLOSEFILE "staff.txt"
OUTPUT "Number of CEOs: ", CEOCount
OUTPUT "Number of non-CEOs: ", NotCEOCount
Key points:
Three READFILE statements inside loop (one for each field)
IF-ELSE to handle both CEO and non-CEO cases
Both counters initialized to 0
Both outputs after the loop
10. Write pseudocode to read a file "numbers.txt" containing one number per line, calculate the sum of all numbers, find the highest and lowest values, and display all three results. [8 marks]
Answer:
DECLARE Line : STRING
DECLARE Number, Sum, Highest, Lowest : INTEGER
DECLARE FirstValue : BOOLEAN
Sum ← 0
FirstValue ← TRUE
OPENFILE "numbers.txt" FOR READ
WHILE NOT EOF("numbers.txt")
READFILE "numbers.txt", Line
Number ← STRING_TO_INT(Line)
Sum ← Sum + Number
IF FirstValue = TRUE THEN
Highest ← Number
Lowest ← Number
FirstValue ← FALSE
ELSE
IF Number > Highest THEN
Highest ← Number
ENDIF
IF Number < Lowest THEN
Lowest ← Number
ENDIF
ENDIF
ENDWHILE
CLOSEFILE "numbers.txt"
OUTPUT "Sum: ", Sum
OUTPUT "Highest: ", Highest
OUTPUT "Lowest: ", Lowest
Key points:
FirstValue flag to initialize Highest/Lowest correctly
Two separate IF statements for Highest and Lowest checks
Sum accumulated in each iteration
Conversion from string to integer if needed
11. Explain the difference between the following file modes: READ, WRITE, and APPEND. Include what happens to existing data in each case. [6 marks]
Answer:
Mode
Purpose
Effect on Existing Data
READ
Read data from the file
Data preserved, cannot be modified
WRITE
Create new file or write to file
All existing data is overwritten/lost
APPEND
Add data to end of file
Existing data preserved, new data added at end
Additional points:
READ mode is read-only - cannot write to file
WRITE mode creates file if it doesn't exist
APPEND is used when you want to add to existing data
Choosing wrong mode can cause data loss
12. What is the purpose of the EOF function? Explain how it is used with a WHILE loop. [4 marks]
Answer:
EOF (End of File) function tests if the end of file has been reached
Returns TRUE if end of file marker has been reached
Returns FALSE if there is more data to read
Used with WHILE NOT EOF(FileName) to read all lines
// Example usage
WHILE NOT EOF("data.txt")
READFILE "data.txt", Line
OUTPUT Line
ENDWHILE
Why use WHILE NOT EOF:
Don't need to know how many lines are in file
Works with files of any size
Prevents errors from trying to read past end of file
WHILE checks condition before reading (safer for empty files)
11. Glossary
Term
Definition
File
A named collection of data stored permanently on a storage device
Text File
A file containing a sequence of characters formatted into lines, each terminated by an end-of-line marker
Filename
The unique identifier for a file, including the extension (e.g., "data.txt")
EOF
End of File - a marker that indicates the end of a file; also a function that returns TRUE when this marker is reached
READ Mode
File mode that allows data to be read from the file without modification
WRITE Mode
File mode that creates a new file or overwrites an existing file; any existing data is lost
APPEND Mode
File mode that adds new data to the end of an existing file while preserving existing content
OPENFILE
Pseudocode command to open a file in a specified mode before reading or writing
CLOSEFILE
Pseudocode command to close a file after operations are complete, freeing resources and saving data
READFILE
Pseudocode command to read one line from an open file into a variable
WRITEFILE
Pseudocode command to write one line of data to an open file
End-of-line Marker
A special character or sequence that marks the end of a line in a text file
End-of-file Marker
A special marker that indicates the end of a file, used by the EOF function
Overwrite
To replace existing data with new data; happens in WRITE mode
Persistent Storage
Storage that retains data even when power is turned off (e.g., files on disk)
12. Exam Success Tips
💡 File Modes - Remember the Rules
READ: Only for reading, data cannot be changed
WRITE: Creates new OR destroys existing data!
APPEND: Adds to end, preserves existing data
Always ask: "Do I need to keep existing data?" → If yes, use APPEND!
💡 The EOF Pattern
Use WHILE NOT EOF(FileName) to read all lines
WHILE is safer than REPEAT for empty files
Each READFILE reads ONE line
EOF() returns TRUE after last line is read
💡 Always Close Files!
CLOSEFILE is essential - marks are often awarded for this
Forgetting to close can cause data loss
Close files after reading AND after writing
Check: Did you close every file you opened?
❌ Common Mistakes to Avoid
Using WRITE when you should use APPEND (destroys data!)
Forgetting to close the file at the end
Using READ mode when trying to write to file
Not using EOF when number of lines is unknown
Reading wrong number of fields for multi-line records
Declaring variables as wrong data type (must be STRING for file operations)
🧠 Memory Tricks
OPEN → PROCESS → CLOSE - Always follow this pattern!
APPEND = Add to end (like appending to a list)
WRITE = Wipe and Write (starts fresh)
EOF = End Of File (signals when to stop reading)
For multi-field records: READ the same number of times as fields
13. Key Takeaways
📌 Summary Points
Why Files Are Needed
Files provide permanent storage for data
Data persists after program ends and computer is turned off
No need to re-enter data when program runs again
File Operations
OPENFILE - Opens file in specified mode (READ, WRITE, APPEND)
READFILE - Reads one line from file into a STRING variable
WRITEFILE - Writes one line of data to file
CLOSEFILE - Closes file and frees resources
File Modes
READ: Read data only, existing data preserved
WRITE: Create new or overwrite existing file
APPEND: Add data to end of existing file
EOF Function
Returns TRUE when end of file is reached
Use with WHILE NOT EOF(FileName) to read all lines