File Handling

Back

Loading concept...

📚 File Handling in C — Your Computer’s Filing Cabinet

Imagine your computer is a giant office with millions of filing cabinets. Each drawer holds papers (data). File handling is like learning to open drawers, read papers, write new ones, and put them back in the right spot!


🗂️ File Handling Overview

What is File Handling?

Think of it like this: When you play a game and save your progress, where does it go? Into a file! Without file handling, every time you close your program, all your work disappears — like writing on water.

File handling lets your C program:

  • 📖 Read data from files (like reading a letter)
  • ✍️ Write data to files (like writing in a diary)
  • 💾 Store information permanently
// Without files: Data vanishes!
int score = 100;  // Gone when program ends

// With files: Data lives forever!
// Save score to "game.txt"

Why Do We Need Files?

Without Files With Files
Data disappears Data stays forever
Can’t share data Easy to share
Limited memory Unlimited storage

📍 FILE Pointer — Your Magic Bookmark

What is a FILE Pointer?

Imagine reading a very long book. You need a bookmark to remember where you are. In C, the FILE * pointer is that bookmark!

FILE *myFile;

This little star * is special — it says “this points to something.” Here, it points to all the information about your file.

The FILE Structure Holds:

  • 📍 Where you are in the file (position)
  • 🔓 Whether file is open or closed
  • 📝 Read mode or write mode
  • ⚠️ Any errors that happened
FILE *diary;      // Bookmark for diary
FILE *gameData;   // Bookmark for game saves
FILE *music;      // Bookmark for music file

Simple Rule: One FILE pointer = One file you’re working with.


🚪 Opening and Closing Files

Opening a File — Knocking on the Door

Before reading a book, you must open it. Same with files!

FILE *fp;
fp = fopen("story.txt", "r");

Breaking it down:

  • fopen = “file open” — knocks on the door
  • "story.txt" = name of the file
  • "r" = what you want to do (read)

What If the File Doesn’t Exist?

FILE *fp = fopen("mystery.txt", "r");

if (fp == NULL) {
    printf("Oops! File not found!");
}

NULL means “nothing” — the file couldn’t be opened!

Closing a File — Saying Goodbye

Always close what you open! Like returning a library book.

fclose(fp);  // Close the file

Why close?

  • Saves all your changes
  • Frees up computer memory
  • Prevents data loss
graph TD A["Start"] --> B["fopen - Open File"] B --> C{Success?} C -->|Yes| D["Work with file"] C -->|No| E["Handle error"] D --> F["fclose - Close File"] F --> G["End"]

🎯 File Modes — Choosing Your Superpower

What Are File Modes?

When you open a file, you tell C what you want to do. It’s like choosing a tool:

Mode Meaning If File Missing
"r" Read only Error!
"w" Write (erases old!) Creates new
"a" Append (add to end) Creates new
"r+" Read AND Write Error!
"w+" Write AND Read Creates new
"a+" Append AND Read Creates new

Examples in Action

// Just reading a recipe
FILE *recipe = fopen("cake.txt", "r");

// Writing a new diary entry (erases old!)
FILE *diary = fopen("diary.txt", "w");

// Adding to shopping list
FILE *list = fopen("shop.txt", "a");

⚠️ Warning About “w” Mode!

// DANGER! This erases everything!
FILE *fp = fopen("important.txt", "w");
// Old content is GONE forever!

Remember: "w" = “wipe and write”


📝 Text vs Binary Mode

What’s the Difference?

Think of it like languages:

  • Text mode = Human language (letters, numbers)
  • Binary mode = Computer language (0s and 1s)

Text Mode (Default)

FILE *fp = fopen("story.txt", "r");
// or explicitly:
FILE *fp = fopen("story.txt", "rt");
  • For: .txt, .csv, .html
  • Readable by humans
  • Each line ends with newline

Binary Mode

FILE *fp = fopen("image.png", "rb");
FILE *game = fopen("save.dat", "wb");

Add b to the mode:

  • "rb" = read binary
  • "wb" = write binary
  • "ab" = append binary

When to Use Which?

Text Mode Binary Mode
Documents Images
Config files Music
Source code Videos
CSV data Game saves
Log files Executables
// Text file
FILE *notes = fopen("notes.txt", "r");

// Binary file (notice the 'b')
FILE *photo = fopen("pic.jpg", "rb");

📖 File Reading Operations

Reading One Character — fgetc()

Like picking up one letter at a time:

FILE *fp = fopen("abc.txt", "r");
char ch = fgetc(fp);  // Gets 'A'
ch = fgetc(fp);       // Gets 'B'
ch = fgetc(fp);       // Gets 'C'
fclose(fp);

Reading a Whole Line — fgets()

Like reading one sentence:

FILE *fp = fopen("story.txt", "r");
char line[100];

fgets(line, 100, fp);
printf("%s", line);  // Prints first line

fclose(fp);

Breaking it down:

  • line = where to store the text
  • 100 = maximum characters to read
  • fp = which file to read from

Reading Formatted Data — fscanf()

Like a smart reader that understands numbers:

// File contains: "Alice 25 85.5"
FILE *fp = fopen("data.txt", "r");

char name[20];
int age;
float score;

fscanf(fp, "%s %d %f", name, &age, &score);
// name = "Alice", age = 25, score = 85.5

fclose(fp);

Reading Until End — The Loop Pattern

FILE *fp = fopen("book.txt", "r");
char ch;

while ((ch = fgetc(fp)) != EOF) {
    printf("%c", ch);  // Print each character
}

fclose(fp);

EOF = “End Of File” — like reaching the last page!

graph TD A["Open File"] --> B["Read character"] B --> C{EOF?} C -->|No| D["Use character"] D --> B C -->|Yes| E["Close File"]

✍️ File Writing Operations

Writing One Character — fputc()

Like writing one letter:

FILE *fp = fopen("letter.txt", "w");
fputc('H', fp);
fputc('i', fp);
fputc('!', fp);
fclose(fp);
// File now contains: Hi!

Writing a String — fputs()

Like writing a whole sentence:

FILE *fp = fopen("note.txt", "w");
fputs("Hello, World!", fp);
fputs("\n", fp);  // New line
fputs("How are you?", fp);
fclose(fp);

Formatted Writing — fprintf()

Like printf() but writes to a file:

FILE *fp = fopen("scores.txt", "w");

char name[] = "Bob";
int score = 95;

fprintf(fp, "Player: %s\n", name);
fprintf(fp, "Score: %d\n", score);

fclose(fp);

File contains:

Player: Bob
Score: 95

Appending — Adding Without Erasing

// Add to existing file
FILE *fp = fopen("log.txt", "a");
fprintf(fp, "New entry!\n");
fclose(fp);
// Old content stays, new content added!

🎯 File Positioning — Moving Your Bookmark

Where Am I? — ftell()

Tells you your current position:

FILE *fp = fopen("story.txt", "r");
fgetc(fp);  // Read 1 character
fgetc(fp);  // Read another

long pos = ftell(fp);  // pos = 2
printf("Position: %ld", pos);

fclose(fp);

Jump Anywhere — fseek()

Move to any position in the file:

fseek(fp, offset, origin);

Origins:

  • SEEK_SET = Start of file (position 0)
  • SEEK_CUR = Current position
  • SEEK_END = End of file

Examples of fseek()

FILE *fp = fopen("data.txt", "r");

// Go to start
fseek(fp, 0, SEEK_SET);

// Go to position 10
fseek(fp, 10, SEEK_SET);

// Move forward 5 from current
fseek(fp, 5, SEEK_CUR);

// Go to end
fseek(fp, 0, SEEK_END);

// Go back 3 from current
fseek(fp, -3, SEEK_CUR);

fclose(fp);

Go Back to Start — rewind()

Quick way to jump to the beginning:

FILE *fp = fopen("book.txt", "r");

// Read some stuff...
fgetc(fp);
fgetc(fp);

// Go back to start
rewind(fp);  // Same as fseek(fp, 0, SEEK_SET)

fclose(fp);
graph TD A["File Start"] --> B["fseek#40;fp, 5, SEEK_SET#41;"] B --> C["Position 5"] C --> D["fseek#40;fp, 3, SEEK_CUR#41;"] D --> E["Position 8"] E --> F["rewind#40;fp#41;"] F --> A

🎁 Complete Example — Putting It All Together

#include <stdio.h>

int main() {
    FILE *fp;

    // Write to file
    fp = fopen("game.txt", "w");
    if (fp == NULL) {
        printf("Error!");
        return 1;
    }
    fprintf(fp, "Score: 100\n");
    fprintf(fp, "Level: 5\n");
    fclose(fp);

    // Read from file
    fp = fopen("game.txt", "r");
    char line[50];
    while (fgets(line, 50, fp)) {
        printf("%s", line);
    }
    fclose(fp);

    return 0;
}

🌟 Quick Reference

Task Function Example
Open file fopen() fopen("f.txt", "r")
Close file fclose() fclose(fp)
Read char fgetc() ch = fgetc(fp)
Write char fputc() fputc('A', fp)
Read line fgets() fgets(buf, 100, fp)
Write string fputs() fputs("Hi", fp)
Read formatted fscanf() fscanf(fp, "%d", &n)
Write formatted fprintf() fprintf(fp, "%d", n)
Get position ftell() pos = ftell(fp)
Set position fseek() fseek(fp, 0, SEEK_SET)
Go to start rewind() rewind(fp)

🎉 Congratulations! You now know how to:

  • Open and close files like a pro
  • Read data from files
  • Write data to files
  • Move around inside files

Files are your program’s long-term memory — use them wisely! 🧠💾

Loading story...

Story - Premium Content

Please sign in to view this story and start learning.

Upgrade to Premium to unlock full access to all stories.

Stay Tuned!

Story is coming soon.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.