File Handling in C

Author Avatar
Learn Here Fun Pedia
5 min read •

C Programming: Mastering File Handling

Up until now, your programs lose all data the moment they close. To keep data permanently, you must store it on the hard drive. C uses file handling to open, read, write, and close physical files on your system.

The Six Core File Functions

  • fopen(): Opens a file and establishes a stream. You choose a mode: read ("r"), write ("w"), or append ("a").
  • fclose(): Closes the open file stream, saving changes and clearing system locks.
  • fprintf(): Writes formatted text strings directly into a file.
  • fscanf(): Reads data out of a file based on specific format specifiers.
  • fgets(): Reads an entire string line safely from a file.
  • fputs(): Writes an entire string line smoothly into a file.

Problem 1: Word Counter Algorithm

This program opens a text file, reads it character by character, and counts the words by identifying blank spaces and newline markers.

#include <stdio.h>

int main() {
    FILE *fp = fopen("sample.txt", "r");
    char ch;
    int words = 0, inWord = 0;

    if (fp == NULL) {
        printf("Could not open file!\n");
        return 1;
    }

    while ((ch = fgetc(fp)) != EOF) {
        if (ch == ' ' || ch == '\n' || ch == '\t') {
            inWord = 0;
        } else if (inWord == 0) {
            inWord = 1;
            words++;
        }
    }

    fclose(fp);
    printf("Total Words: %d\n", words);
    return 0;
}

Problem 2: File Duplicator (Copy File)

We read every byte from a source file and clone it cleanly into a destination file block.

#include <stdio.h>

int main() {
    FILE *src = fopen("source.txt", "r");
    FILE *dest = fopen("destination.txt", "w");
    char ch;

    if (src == NULL || dest == NULL) {
        printf("File access error!\n");
        return 1;
    }

    while ((ch = fgetc(src)) != EOF) {
        fputc(ch, dest);
    }

    fclose(src);
    fclose(dest);
    return 0;
}

Problem 3: Persistent Student Database Manager

This system saves structural records safely onto the hard drive and reads them back out cleanly.

#include <stdio.h>

struct Student {
    int id;
    char name[20];
};

int main() {
    FILE *fp = fopen("students.dat", "w+");
    struct Student s1 = {101, "Raj"};
    struct Student s2;

    // Write structure data safely into our file stream
    fprintf(fp, "%d %s\n", s1.id, s1.name);

    // Rewind the file position back to index zero
    rewind(fp);

    // Read the structure file back out into our empty memory folder
    fscanf(fp, "%d %s", &s2.id, s2.name);
    printf("Loaded Record: ID: %d, Name: %s\n", s2.id, s2.name);

    fclose(fp);
    return 0;
}

Summary

File handling transfers dynamic data out of volatile RAM and locks it permanently into hard drive storage streams using the robust FILE * controller type.

➔ Read more about Data Types ➔ Read more about Fundamentals ➔ Read more about Variables and Storage Classes ➔ Read more about String ➔ Read more about Operators ➔ Read more about Control Statements and Loops in C ➔ Read more about Functions ➔ Read more about Arrays ➔ Read more about Pointers ➔ Read more about Structures ➔ Read more about Enum ➔ Read more about Union

Comments (0)