Section A — 1 Mark Questions
1. Define file handling. [1 Mark]
Answer: File handling is the process of creating, reading, writing, and closing files in a computer program to store data permanently.
2. What is the primary purpose of opening a file? [1 Mark]
Answer: Opening a file allocates memory and creates a stream or link between the program and the physical file on the storage device.
3. Why is it important to close a file after operations are complete? [1 Mark]
Answer: Closing a file ensures that all data is flushed from the buffer to the storage and releases the system resources used by the file.
4. What happens if you try to open a non-existent file in read mode? [1 Mark]
Answer: The program will typically throw an error or raise an exception indicating that the file could not be found.
5. Which operation is used to retrieve data from a file into the program memory? [1 Mark]
Answer: The read operation.
6. Which operation is used to transfer data from the program to a file? [1 Mark]
Answer: The write operation.
7. What is a file pointer? [1 Mark]
Answer: It is an internal marker that keeps track of the current position within a file during reading or writing.
8. What does the 'mode' parameter determine in file handling? [1 Mark]
Answer: It determines the purpose for which the file is opened, such as reading, writing, or appending.
9. If a file is opened in 'write' mode, what happens to existing content? [1 Mark]
Answer: The existing content is usually truncated or overwritten entirely.
10. Can multiple files be open simultaneously in a single program? [1 Mark]
Answer: Yes, most programming languages allow multiple files to be open at the same time.
11. Is a file considered a form of persistent storage? [1 Mark]
Answer: Yes, files provide non-volatile storage that retains data after the program terminates.
12. What does 'read-only' mode imply? [1 Mark]
Answer: It implies that the file can only be accessed for extracting data and cannot be modified.
13. Does the write operation require explicit saving? [1 Mark]
Answer: It requires the close operation to ensure the buffer is flushed and data is permanently saved.
14. What is a text file? [1 Mark]
Answer: A file containing data formatted as plain characters, readable by text editors.
15. What happens if an error occurs while writing to a file? [1 Mark]
Answer: The write operation fails, and proper error handling is required to manage the exception.
16. What does a file object represent? [1 Mark]
Answer: It represents the interface used to perform operations on the underlying physical file.
17. Is it necessary to open a file before performing any read or write operation? [1 Mark]
Answer: Yes, the program must establish a connection via the open operation first.
18. What is a buffer in file handling? [1 Mark]
Answer: A temporary storage area in memory that holds data before it is written to the disk or after it is read from the disk.
19. Define append mode. [1 Mark]
Answer: A mode that opens a file for writing, adding new data to the end of the existing content instead of overwriting it.
20. Why is closing a file good programming practice? [1 Mark]
Answer: It prevents memory leaks and data corruption.
Section B — 2/3 Mark Questions
1. Differentiate between reading and writing a file. [2 Marks]
Answer: Reading is the process of accessing or retrieving data stored in a file, whereas writing is the process of sending data from the program and storing it into the file.
2. Explain the role of the 'open' function in file handling. [2 Marks]
Answer: The open function creates a communication bridge between the program and the file. It specifies the file path and the mode of operation (read, write, or append) and returns a handle to the file object.
3. Why should a programmer always close a file? [3 Marks]
Answer: First, it prevents data loss by ensuring all data from the memory buffer is flushed to the disk. Second, it frees up system resources and file handles for other parts of the application. Third, it avoids file locking issues where other processes might be unable to access the file.
4. What is the difference between write mode and append mode? [2 Marks]
Answer: Write mode creates a new file or overwrites an existing file's contents entirely. Append mode preserves existing data and adds new data to the end of the file.
5. Describe what happens when a program attempts to write to a closed file. [2 Marks]
Answer: The program will typically trigger a runtime error because the file handle/pointer no longer exists, and there is no valid stream to send the data through.
6. Briefly explain the function of a file handle. [3 Marks]
Answer: A file handle is an abstract reference or variable that allows the programmer to interact with an open file. It maintains the current state of the file, such as the position of the file pointer, and provides methods to trigger I/O operations like reading or writing.
7. What is a file stream? [2 Marks]
Answer: A file stream is a sequence of data flowing from the program to the file (output stream) or from the file to the program (input stream) during processing.
8. What is an error in file handling? Give an example. [3 Marks]
Answer: File errors occur when file operations cannot be completed as expected. For example, a 'File Not Found' error occurs when the program attempts to open a file that does not exist in the specified directory, or 'Permission Denied' occurs when trying to write to a read-only file.
9. How do files contribute to permanent storage? [2 Marks]
Answer: Unlike variables which are stored in volatile RAM and lost when a program exits, files are stored on non-volatile media (like hard drives or SSDs), ensuring data persists after the program closes.
10. Can a file be opened in both read and write mode? [2 Marks]
Answer: Yes, many languages support modes like 'r+' or 'w+' which allow both reading and writing to the same file descriptor simultaneously.
Section C — 5 Mark Questions
1. Explain the standard lifecycle of file handling in a programming environment. [5 Marks]
Answer: The lifecycle of file handling involves a sequence of essential steps to ensure data integrity and program stability:
Steps
- Opening: The file is accessed using an open function. The programmer must specify the file path and the mode (e.g., 'r' for read, 'w' for write). This step returns a file handle.
- Processing: Once opened, the program performs operations. If in read mode, data is extracted from the file into memory. If in write mode, data is transferred from memory to the file buffer.
- Closing: After completing the task, the file must be explicitly closed. This flushes the buffers to physical storage and releases system resources.
Importance: Following this lifecycle prevents data corruption and ensures that system memory is not exhausted by dangling file pointers.
2. Discuss the importance of file modes and their specific applications. [5 Marks]
Answer: File modes are critical because they define the access permissions and the behavior of the file pointer during operations.
Common Modes
- Read Mode ('r'): Used for accessing existing data. The file pointer is placed at the beginning. It is the default mode and is used for data analysis or reporting.
- Write Mode ('w'): Used for creating new files or replacing existing ones. If the file exists, its data is discarded. It is useful for generating new output files.
- Append Mode ('a'): Used for logging or extending data. New data is placed at the end of the file, preserving history.
Application: Selecting the correct mode prevents accidental data deletion and ensures that the program behaves predictably when interacting with the file system.
3. Explain the concept of file buffers and why they are used during write operations. [5 Marks]
Answer: A buffer is a small, temporary region of RAM used to hold data during the transfer process between the application and the physical hard drive.
Working Principle
Writing directly to a disk for every single piece of data is slow due to physical hardware latency. Instead, data is collected in a buffer. Once the buffer is full or the program calls the close function, the entire batch of data is flushed to the storage medium at once.
Key Advantages
- Performance: Reduces the number of expensive disk access requests.
- Efficiency: Optimizes data throughput.
- Integrity: Closing the file ensures that the last few bits in the buffer are correctly written, which is why explicit closing is mandatory.
Observation: If a program crashes without closing the file, data left in the buffer may be permanently lost.
4. Describe the differences between text files and the general necessity of file handling. [5 Marks]
Answer: File handling is the essential mechanism that allows software to interact with long-term storage.
Necessity of File Handling
Programs are inherently transient; variables and memory contents vanish when the program stops. File handling provides a way to maintain state, store configurations, and export results for future use.
Text Files
Text files are a common format for storage, consisting of characters that follow a standard encoding (like ASCII or Unicode). They are human-readable, portable across different operating systems, and easy to debug. They are commonly used for configuration settings, logs, and simple data storage. In comparison to binary files, text files provide a simpler abstraction where data is handled as lines and characters rather than raw bytes.
Conclusion: Understanding how to manage these files correctly is foundational for building functional applications that require data persistence.
5. Discuss the risks associated with improper file handling and how they can be mitigated. [5 Marks]
Answer: Improper file handling is a major source of bugs, ranging from data corruption to memory leaks and security vulnerabilities.
Common Risks
- Data Loss: Forgetting to close a file after writing may prevent data from being physically saved to the disk.
- Resource Leaks: Opening many files without closing them can reach the operating system's limit for open file handles, causing the program or system to crash.
- Overwriting Errors: Accidentally using 'write' mode instead of 'append' mode can lead to the permanent loss of historical data.
Mitigation Strategies
- Exception Handling: Always use try-finally blocks or language-specific constructs (like 'with' statements) to ensure files close automatically even if an error occurs.
- Mode Checking: Carefully select the mode and verify file existence before attempting to open it.
- Explicit Closing: Make it a strict coding standard to close files as soon as their task is complete to release system resources promptly.