📁
File Handling — Part 1
🏠 Home Lecture 22: File Intro
The Problem ⚡

Why do we need File Handling?

So far, every program we wrote stores data in RAM (variables, arrays, structs). What happens to this data when you close the program or turn off the computer?

💡 The RAM vs HDD Challenge

How can we save student records so they are still there tomorrow?
Keep the program running forever
Save them to a File on the Hard Disk
Use a larger Array
Use Global Variables
💾 File Handling means:

1. Taking data from RAM → Storing to a File.
2. Reading data from a File → Bringing to RAM.
In C, files are treated as a stream of bytes. To manage them, C provides a standard library <stdio.h> with specific functions and a special pointer type: FILE *.
Basic Flow

4 Steps to Handle Any File

Whenever you work with files in C, you must ALWAYS follow these 4 steps in order. Missing a step (like closing) can cause data loss!

1. Declare Pointer

Create a FILE * pointer.

→

2. Open File

Use fopen() with a mode.

→

3. Process (Read/Write)

Use functions like fprintf().

→

4. Close File

Use fclose() to save safely.

file_flow.cHover to explore ✶
// Step 1: Declare a FILE pointer FILE *ptr; // Step 2: Open the file ptr = fopen("data.txt", "w"); if (ptr == NULL) { printf("Error opening file!"); return 1; } // Step 3: Process the file (Write data) fprintf(ptr, "Hello, File!"); // Step 4: Close the file fclose(ptr);
Modes

File Opening Modes in C

When you use fopen(), you must specify how you want to open the file (Read, Write, or Append).

Mode Meaning What happens?
"r" Read Opens file for reading. If the file does not exist, fopen returns NULL.
"w" Write Opens file for writing. If file exists, its content is erased (overwritten). If it doesn't exist, a new file is created.
"a" Append Opens file to add data at the end. Data is NOT erased. If it doesn't exist, a new file is created.
"r+" Read + Write Opens for both reading and writing. File must exist.
"w+" Write + Read Opens for both. Like "w", existing content is erased first.
"a+" Append + Read Opens for both. Reading is from the beginning, but writing always happens at the end.
⚠️ DANGER with "w" mode: Never use "w" if you want to keep old data. It instantly wipes the file clean the moment fopen() is executed! Use "a" instead!
Knowledge Check ✍

Let's test what you've learned!

Question 1 of 3
Loading...