C Programming - Beginner to Brilliance / File Handling in C

Introduction to File Handling

📌 What is File Handling?

Imagine writing your homework in a notebook — if you don’t write it down and just keep it in your head, it’s lost when you sleep or get distracted.

Similarly, when a program runs, all the data is stored in temporary memory (RAM). Once the program ends, everything is erased.

So, if we want to:

  • Save data permanently ✅

  • Share data with other programs or people ✅

  • Maintain logs, backups, settings ✅

We need to store that data in a file.

👉 That’s where File Handling in C comes in — it allows your C program to create, read, write, append, and manipulate files on disk using specific functions from the standard library (stdio.h).


🔁 Why File Handling is Needed?

Without Files

With File Handling

Data lost after program ends ❌

Data is stored permanently ✅

Cannot share output ❌

Output can be shared via files ✅

Manual re-entry needed ❌

Reuse stored data anytime ✅


📦 Types of Files in C

  1. Text Files (.txt)

    • Data is stored as readable characters

    • Can open the file in Notepad or any editor

    • E.g., report.txt, log.txt

    • Used for config, reports, user data

  2. Binary Files (.bin)

    • Data is stored in binary format (0s and 1s)

    • Not readable by humans

    • Smaller, faster, more efficient

    • Used for high-performance apps, storing structures, images, etc.


⚙️ Core File Operations in C

All file handling is done through a file pointer, using the FILE type from the C standard library.

#include <stdio.h>

FILE *fp;  // file pointer

🟢 Opening a File – fopen()


🔴 Closing a File – fclose()

This:

  • Frees memory

  • Saves the file properly

  • Prevents data corruption


📖 Reading from Files

🅰️ fgetc(fp) – Read a single character

char ch = fgetc(fp);

🅱️ fgets(str, size, fp) – Read a full line or string

char line[100];
fgets(line, 100, fp);

🅾️ fscanf(fp, "%d %s", &num, str) – Formatted input

Like scanf, but from a file.

✅ Example:

#include <stdio.h>

int main() {
    FILE *fp = fopen("input.txt", "r");
    if (fp == NULL) {
        printf("File could not be opened.\\n");
        return 1;
    }

    int num;
    char str[50];

    fscanf(fp, "%d %s", &num, str);
    printf("Read values: %d and %s\\n", num, str);

    fclose(fp);
    return 0;
}

📝 Contents of input.txt:

100 CodeVeda

✍️ Writing to Files

✏️ fputc('A', fp) – Write one character

#include <stdio.h>

int main() {
    FILE *fp = fopen("char.txt", "w");
    if (fp == NULL) {
        printf("File could not be opened.\\n");
        return 1;
    }

    fputc('A', fp);
    fputc('\\n', fp);  // newline
    fclose(fp);

    printf("Character written to char.txt\\n");
    return 0;
}

✍️ fputs("Hello", fp) – Write a string

#include <stdio.h>

int main() {
    FILE *fp = fopen("string.txt", "w");
    if (fp == NULL) {
        printf("File could not be opened.\\n");
        return 1;
    }

    fputs("Hello", fp);
    fputs("\\nWorld!", fp);
    fclose(fp);

    printf("String written to string.txt\\n");
    return 0;
}

🧾 fprintf(fp, "Name: %s", name) – Formatted output (like printf)

#include <stdio.h>

int main() {
    FILE *fp = fopen("formatted.txt", "w");
    if (fp == NULL) {
        printf("File could not be opened.\\n");
        return 1;
    }

    char name[] = "CodeVeda";
    int age = 21;

    fprintf(fp, "Name: %s\\n", name);
    fprintf(fp, "Age: %d\\n", age);

    fclose(fp);
    printf("Formatted data written to formatted.txt\\n");
    return 0;
}

📍 Positioning in File (Advanced)

To move around inside the file (like skipping lines or jumping back):

Function

Use

fseek(fp, offset, SEEK_SET)

Move to a position

ftell(fp)

Get current position

rewind(fp)

Go to the start


⚠️ Always Check for Errors

Before using the file, check if it opened properly:

fp = fopen("data.txt", "r");
if (fp == NULL) {
    printf("Error opening file.\\n");
}

fopen() returns NULL if file doesn’t exist or can’t be opened.


🧠 Summary

Real Life

C File Handling

Opening notebook

fopen()

Writing in notebook

fprintf()

Reading a sentence

fgets()

Closing notebook

fclose()