📑 Contents

Chapter 10.3: File Handling in Pseudocode

9618 AS Computer Science

📚 Learning Objectives
📋 Prior Knowledge Required
🌟 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!

PROGRAM Variables in Memory TEXT FILE .txt extension Read/Write DISK Permanent Storage

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
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:

MEMORY (RAM) Variables, Arrays ❌ Lost when power off TEMPORARY FILE STORAGE Text Files (.txt) ✓ Saved permanently PERMANENT Program Starts Program Ends / Power Off Later

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
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.

OPEN File Step 1 READ or WRITE Step 2 PROCESS Data Step 3 CLOSE File Step 4

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.

3.2 Example: Reading a Single Line

OPENFILE "StudentData.txt" FOR READ DECLARE StudentName : STRING READFILE "StudentData.txt", StudentName OUTPUT StudentName CLOSEFILE "StudentData.txt"

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>)

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.

StudentData.txt Line 1: "Alice" Line 2: "Bob" Line 3: "Charlie" [EOF Marker] Read pointer WHILE NOT EOF Keep reading... until EOF = TRUE EOF() returns FALSE while reading EOF() returns TRUE at marker

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

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

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.

WRITE Mode Old Data 1 Old Data 2 New Data 1 New Data 2 ↑ Overwrites! APPEND Mode Old Data 1 Old Data 2 New Data 1 New Data 2 ↑ Added to end! vs ■ Preserved ■ Added ■ Lost

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

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
⚠️ 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.

BEFORE Append 1. Alice 2. Bob 3. Charlie EOF APPEND AFTER Append 1. Alice 2. Bob 3. Charlie 4. Mansoor ✓ 5. Mehrin ✓ ← EOF moved

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
  1. Opens file in WRITE mode
  2. Loops to get user input until blank line entered
  3. Writes each non-blank line to file
  4. Closes file when input is complete
  5. Reopens file in READ mode
  6. Reads and outputs each line until EOF
  7. Closes file again
Identifier Data Type Description
textLine STRING Line of text read from/written to file
myFile STRING File name ("myText.txt")
INPUT User types text WRITEFILE Save to file FILE myText.txt Lines stored READFILE Load from file OUTPUT Display lines EOF check Loop until blank

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!

staff.txt John Smith 45 CEO Record 1 Jane Doe 30 Manager Record 2 Bob Wilson 55 CEO Record 3 READFILE → Name READFILE → Age READFILE → Position IF Position = "CEO" Count + 1

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
A B C D ARRAY [1] [2] [3] [4] FOR loop WRITEFILE FILE A B C D Each element becomes a separate line

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
Step 1: Line 1 ← LineX LineY LineZ Step 2: Line 2 Line 1 ← LineX ← LineY LineZ Step 3: Line 3 Line 2 Line 1 ← LineX ← LineY ← LineZ Data shifts down as new lines are read After EOF: LineZ has oldest, LineX has 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:

  1. Open file in APPEND mode
  2. Prompt and input a student name and mark
  3. If mark is less than 20, write the name to the file
  4. Repeat steps 2-3 for all 35 students
  5. 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]

Answer:

PROCEDURE LastLines(FileName : STRING) DECLARE LineX, LineY, LineZ : STRING DECLARE CurrentLine : STRING LineX ← "" LineY ← "" LineZ ← "" OPENFILE FileName FOR READ WHILE NOT EOF(FileName) LineZ ← LineY LineY ← LineX READFILE FileName, LineX ENDWHILE CLOSEFILE FileName OUTPUT LineZ OUTPUT LineY OUTPUT LineX ENDPROCEDURE

Key points:

  • 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
💡 The EOF Pattern
💡 Always Close Files!
❌ Common Mistakes to Avoid
🧠 Memory Tricks
QUICK REFERENCE CHECKLIST ✓ OPENFILE first ✓ Choose correct mode ✓ READFILE/WRITEFILE ✓ Use EOF for loops ✓ CLOSEFILE last! MODE GUIDE: READ → Get data WRITE → New/Replace APPEND → Add to end REMEMBER: Variables = STRING 1 READFILE = 1 line 1 WRITEFILE = 1 line

13. Key Takeaways

📌 Summary Points

Why Files Are Needed

File Operations

File Modes

EOF Function

⚠️ Exam Essentials
🌟 Final Tips
FILE HANDLING WORKFLOW WRITING TO FILE 1. OPENFILE "name.txt" FOR WRITE 2. WRITEFILE "name.txt", data 3. CLOSEFILE "name.txt" READING FROM FILE 1. OPENFILE "name.txt" FOR READ 2. WHILE NOT EOF("name.txt") READFILE "name.txt", var 3. CLOSEFILE "name.txt" Data flows from program to file (write) or file to program (read)