NBC 103 • Unit 516 min readHigh Exam Frequency

File Handling Fundamentals: Streams, Modes & Character/Line I/O

Unit 5: Searching, Sorting, Dynamic Memory & File HandlingProblem Solving Using C

👨‍🏫 Professor's Mental Model: The Secure Warehouse Filing Cabinet & Courier Conveyor

RAM ek aisi temporary table hai jisme program band hote hi sab kuch gayab ho jata hai (Volatile)! Agar data ko hamesha ke liye save rakhna hai toh use Hard Disk ki file me store karna padta hai (Non-Volatile). FILE pointer ek courier boy jaisa hai jo file ka darwaza kholta hai (fopen), data ko ek-ek karke stream karta hai, aur kaam khatam hote hi darwaza lock karke chabi lauta deta hai (fclose)! Agar lock nahi lagaya toh data corruption ho sakta hai!

Academic Lecture Notes & Solved Study Pages

Unit 5 • Core Concepts, Step-by-Step Proofs & Notebook Solutions

4 Notebook Pages
NOTEBOOK PAGE 1 OF 4

1. The Need for File Persistence & The FILE Structure Pointer

Volatile vs Non-Volatile: RAM loses all state upon program termination. File handling allows storing permanent records on Hard Drives / SSDs.
Concept of Streams: C treats all external files as a continuous, unidirectional sequence of raw bytes called a stream.
The FILE Structure: Defined in `<stdio.h>`, `FILE` is an internal system structure holding file metadata (file descriptor, current buffer position pointer, error flags, file access mode).
Declaration: `FILE *fp;`
NOTEBOOK PAGE 2 OF 4

2. Opening Files with fopen() & The 6 Primary Access Modes

Syntax: `FILE *fp = fopen("filename.txt", "mode");`

The 6 Standard Text File Modes:

1. "r" (Read): Opens existing file for reading. Returns NULL if file does not exist.

2. "w" (Write): Creates a new empty file for writing. If file already exists, ITS CONTENTS ARE COMPLETELY TRUNCATED (ERASED)!

3. "a" (Append): Opens file for writing at the END. Preserves existing data. Creates new file if missing.

4. "r+" (Read + Write): Opens file for both reading and writing. File must exist.

5. "w+" (Read + Write): Creates new empty file for read/write. Erases existing content.

6. "a+" (Read + Append): Opens for read and append at end.

NOTEBOOK PAGE 3 OF 4

3. Closing Files with fclose() & Safe Error Checking

Always verify file open status:

`if (fp == NULL) { printf("File could not be opened!"); exit(1); }`

Why fclose(fp) is mandatory:

Operating systems buffer file writes in RAM. Calling `fclose()` forcefully flushes buffered data to physical disk platter, releases OS file locks, and frees the file descriptor table entry.

NOTEBOOK PAGE 4 OF 4

4. Character and String File I/O Functions

Character I/O:
- `fgetc(fp)`: Reads a single character from file. Returns `EOF` (-1) when reaching End-Of-File.
- `fputc(ch, fp)`: Writes a single character to the file.
Line/String I/O:
- `fgets(str, n, fp)`: Reads up to $n-1$ characters or until newline.
- `fputs(str, fp)`: Writes null-terminated string to file.
Formatted File I/O:
- `fprintf(fp, "format", args...)`: Formatted writing to file stream.
- `fscanf(fp, "format", &args...)`: Formatted reading from file stream.
Master File Opening Modes Specification Matrix
ModeOperation AllowedIf File Already ExistsIf File Does Not ExistInitial File Pointer Position
"r"Read OnlyOpens normallyFails: Returns NULL pointerBeginning of file
"w"Write OnlyCompletely OVERWRITES & erases contentCreates new empty fileBeginning of file
"a"Append (Write)Preserves existing dataCreates new fileEnd of file (EOF)
"r+"Read & WritePreserves existing dataFails: Returns NULL pointerBeginning of file
"w+"Read & WriteErases existing data completelyCreates new empty fileBeginning of file
"a+"Read & AppendPreserves existing dataCreates new fileEnd of file for writes

Interactive Tested Code Example

#include <stdio.h>
#include <stdlib.h>

int main(void) {
    FILE *fp;
    char filename[] = "sample_notes.txt";

    // 1. Write formatted data to file
    fp = fopen(filename, "w");
    if (fp == NULL) {
        printf("Error: Unable to create file.\n");
        return 1;
    }
    fprintf(fp, "DevBCA University Portal\n");
    fprintf(fp, "Course: Problem Solving Using C\n");
    fprintf(fp, "Score: %d Marks\n", 100);
    fclose(fp); // Flush and close file

    // 2. Read contents back using fgetc until EOF
    fp = fopen(filename, "r");
    if (fp == NULL) {
        printf("Error: Unable to open file for reading.\n");
        return 1;
    }

    printf("=== READING FILE STREAM CONTENTS ===\n");
    int ch;
    while ((ch = fgetc(fp)) != EOF) {
        putchar(ch); // Echo character to terminal
    }
    fclose(fp);
    return 0;
}
💡 Note:Demonstrates full file handling workflow: opening in write mode, writing formatted strings via fprintf(), closing, reopening in read mode, and streaming characters with fgetc() until EOF.

🎯 University Exam Scoring Blueprint

  • In university exams, always check if (fp == NULL) after every fopen call.
  • Emphasize that fgetc() returns an 'int', NOT a char, because EOF is defined as integer -1 which exceeds 8-bit unsigned char.
  • Remember that mode 'w' immediately destroys and truncates existing file contents.

Top Viva Questions on File Handling Fundamentals: Streams, Modes & Character/Line I/O

2 Questions
1

Why is the return type of fgetc() int rather than char?

2

What is EOF and what numerical value does it hold?