Skip to main content

File Handling in C

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

Popular posts from this blog

How I Got Selected in MNC

Virtusa Sometimes success does not come from having the best coding skills or the perfect roadmap. Sometimes it comes from simply refusing to quit. This is the honest story of how I transitioned from a confused, rejected fresher to getting selected as an Associate Engineer at Virtusa. The Beginning: Confused About My Future After completing my graduation, I stared blankly at my career options. Like many freshers, I lacked a clear direction. Should I join a Java course? Should I prepare on my own? Should I just wait for campus placement opportunities? One day, I called my friend Chetan. He suggested I join Naresh i Technologies and start learning Java seriously. Still unsure of my path, I told him I needed time to think about it. A couple of days later, my phone buzzed with a WhatsApp message offering a job opportunity. They asked me to come for the next round of the recruitment process. Excitement completely took over. I packed my bags, traveled to th...

Spring Boot Introduction

Spring Boot Introduction: Architecture, Dependencies, and Embedded Servers Modern enterprise applications demand rapid development, frictionless deployment, and absolute minimal configuration. Before Spring Boot arrived, developers utilizing the Spring Framework wasted immense amounts of time configuring XML files, managing clashing dependencies, setting up clunky application servers, and stitching various Spring modules together manually. To eliminate these bottlenecks, Pivotal introduced Spring Boot . Built entirely on top of the traditional Spring Framework, Spring Boot is an "opinionated" framework. It aggressively simplifies application development by injecting auto-configuration, packaging starter dependencies, and embedding web servers directly into your application. This allows backend developers to focus entirely on building business logic rather than wrestling with infrastructure setup. What is Spring Boot? Spring Boot is a powerful extens...

Data Types in C

C Programming: Understanding Data Types Think of your kitchen. You store a large bag of flour in a big bin, a pinch of saffron in a tiny jar, and milk in a liquid measuring jug. You do not put liquids into paper bags, and you do not use a massive bucket for a single teaspoon of sugar. C programming works the exact same way. When you create a variable, you must tell the computer exactly what kind of "container" to build in its memory. We call these containers Data Types . They dictate what kind of data the container holds, how much space it takes up, and what operations you can perform on it. 1. Primitive Data Types C offers several built-in, "primitive" data types. Think of these as the fundamental storage containers. int (Integer): You use this to store whole numbers without decimals. Real-life example: Counting the number of people in a room or tracking a player's score in a video game. char (Character): You use this ...