Questions
2–3 questions in university theory papers
Difficulty
Medium
Importance
Essential for lab practicals and coding theory.
Overview
File handling is a critical mechanism in programming that allows data to be stored and retrieved from secondary storage, providing persistence beyond program execution. For university examinations, mastering this topic involves understanding the stream-based architecture, proper mode selection for file operations, and the distinction between accessing data linearly versus jumps. It is a fundamental skill for implementing real-world applications that process datasets.
File Modes
File modes define the permission and the cursor position relative to the file content at the time of opening. Understanding these modes is essential for preventing data loss and ensuring the file pointer behaves as expected.
- r: Open for reading; error if file missing.
- w: Open for writing; truncates file to zero length.
- a: Open for appending; data added at the end.
- r+: Open for reading and writing.
- b: Binary mode flag for non-text data.
Read and Write Operations
Read and write operations involve transferring data between the program's buffer and the external storage media. Proficiency in using functions like fread, fwrite, fprintf, and fscanf is required to handle data streams efficiently.
- fprintf/fscanf: Formatted I/O operations.
- fgetc/fputc: Single character I/O functions.
- fgets/fputs: Line-based string I/O handling.
- fread/fwrite: Block-level binary data transfer.
- EOF: End-of-file condition indicator.
Sequential vs Random Access
Sequential access requires reading or writing data in a continuous stream from start to finish, while random access allows moving to a specific byte location within the file. Controlling the file pointer is the primary difference between these approaches.
- fseek(FILE *stream, long offset, int whence): Moves pointer.
- ftell(FILE *stream): Returns current position.
- rewind(FILE *stream): Resets pointer to beginning.
- SEEK_SET: Offset from beginning of file.
- SEEK_CUR: Offset from current position.
- SEEK_END: Offset from end of file.
Exam Tip
Always verify that your file pointer is not NULL immediately after fopen() and consistently use fclose() before the function returns to ensure all buffers are flushed.
Common Mistakes
- Failing to close a file using fclose(), leading to resource leaks and potential data corruption.
- Confusing the 'w' mode with 'a' mode, resulting in the accidental deletion of existing file content.
- Neglecting to check the return value of fopen() for NULL, which leads to segmentation faults when attempting to access a non-existent file.
More Revision Notes
Ready to test yourself?
Play topic-wise File Handling questions in Aspirant Arcade — gamified MCQ practice.
Download Free