File handling
In programming, variables are stored in RAM (Random Access Memory). RAM is volatile, meaning its contents are lost when the computer is switched off. To keep data permanently, we must store it in a file on secondary storage (like a hard drive).
Storing data in a file serves two main purposes:
- Persistence: It creates a permanent copy of the data that survives program termination or power loss.
- Reusability: The data can be recalled later by the same program or accessed by a different program.
| Description & Syntax |
|---|
| Opens a file to prepare it for use. You must specify the filename and the mode. Syntax: OPENFILE \text{ filename } FOR \text{ READ/WRITE} |
| Retrieves data from an open file into a variable. Syntax: READFILE \text{ filename, variable} |
| Sends data from a variable to the open file. Syntax: WRITEFILE \text{ filename, variable} |
| Closes the file connection. This is essential to save changes and free up system resources. Syntax: CLOSEFILE \text{ filename} |
We use the mode FOR WRITE because we are creating or overwriting data.
OPENFILE \text{ MyPassword.txt } FOR WRITE
We specify the filename and the variable containing the data.
WRITEFILE \text{ MyPassword.txt, Password }
This saves the data permanently to the disk.
CLOSEFILE \text{ MyPassword.txt }
Correction: You must use FOR WRITE (or FOR APPEND) if you are adding or changing data. Using FOR READ will cause an error because the file is not prepared for writing.
Correction: You must use FOR READ if you are retrieving data. Opening a file for writing when it already contains important data may overwrite (delete) that existing content.
Context: Use this when explaining the purpose of file handling.
Reasoning: Examiners accept answers that explicitly mention the volatile nature of RAM versus the permanent nature of secondary storage. They also accept answers regarding data sharing between programs.
Correct Phrasing Examples:
- "To create a permanent copy of the data so it is not lost when the program closes."
- "To allow the data to be recalled or used again in a future session."
- "To enable the data to be transferred to another computer or accessed by another program."
Incorrect Phrasing: Avoid vague answers like 'to save data' without specifying permanence or retrieval. Do not say 'to open the file' as that is an action, not a reason.
- Data is stored permanently (prevents data loss when power is lost).
2. Data can be recalled/used again later or by another program.
- OPENFILE \text{ Hotel.txt } FOR WRITE
2. WRITEFILE \text{ Hotel.txt, Name }
3. CLOSEFILE \text{ Hotel.txt }