File Handling (Copy)
IGCSE / O Level Computer Science Cheat Sheet
Topic: 8.3 File Handling
📁 Why Use Files?
- Files allow programs to store data permanently
- Data remains available even after the program ends
- Useful for saving user data, logs, configurations, etc.
📂 File Operations
| Operation | Description |
|---|---|
| Open | Prepares the file for reading or writing |
| Read | Retrieves data from the file |
| Write | Stores data into the file |
| Close | Finalizes file use and releases resources |
🔄 Opening a File
OPENFILE myFile FOR READ
OPENFILE myFile FOR WRITE
📥 Reading from a File
| Read Method | Description | Example |
|---|---|---|
| READ | Reads a single item | READ myFile, name |
| READLINE | Reads a full line of text | READLINE myFile, sentence |
📤 Writing to a File
| Write Method | Description | Example |
|---|---|---|
| WRITE | Writes an item to the file | WRITE myFile, "Hello" |
| WRITELINE | Writes a full line to the file | WRITELINE myFile, sentence |
❌ Closing the File
CLOSEFILE myFile
- Prevents data loss
- Releases system resources
⚠️ File Access Modes
| Mode | Purpose |
|---|---|
| READ | Opens file to read data only |
| WRITE | Opens file to write (overwrites existing data) |
📋 Good Practice
- Always open a file before use
- Always close the file after reading/writing
- Check if the file exists (when reading) to avoid errors
- Use loops to read or write multiple lines
🔁 Example: Reading a File Line by Line
OPENFILE scores FOR READ
WHILE NOT EOF(scores)
READLINE scores, line
OUTPUT line
ENDWHILE
CLOSEFILE scores
🔁 Example: Writing Data to a File
OPENFILE log FOR WRITE
WRITELINE log, "Program started"
WRITELINE log, "User logged in"
CLOSEFILE log
