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.

Comments

Popular posts from this blog

Strings in C

C Programming: Working with Strings Unlike modern programming languages like Python or Java, C does not possess a dedicated "String" data type. Instead, C treats a string as a simple 1D array of characters. Real-life example: Think of a freight train. The train does not exist as one solid object; it consists of individual boxcars linked together. Similarly, a C string links individual characters side-by-side in memory. To let the computer know the train has ended, C attaches a special "caboose" called the Null Terminator ( \0 ). 1. Essential String Functions Handling strings manually requires complex loops. To save time, C provides a built-in library called <string.h> that contains powerful functions to manipulate text. strlen(): You use this to find the exact length of a string. The compiler counts the characters until it hits the \0 terminator. It does not count the terminator itself. strcpy(): You use...

Graph Algorithms

Graph Algorithms: Navigating Complex Networks Graphs represent the absolute pinnacle of data structure interview questions for top-tier tech companies. Why? Because the modern digital world runs entirely on graph networks. When you search for the fastest route on Google Maps, you traverse a graph of cities and roads. When you view friends on Facebook or connections on LinkedIn, you query a graph of users. Even the underlying architecture of Git commits, internet routers, and microservice dependencies rely purely on graph theory. 1. What is a Graph? A graph abandons the strict top-down hierarchy of a Tree. Instead, it forms a free-flowing network built from two core components: Vertices (Nodes): The actual data points in the network (e.g., specific cities, or specific users). Edges: The physical or logical connections linking those nodes together (e.g., the highways between cities). Graph Terminology & Types To manipulate graphs effici...

Programming For Problem Solving

What are General Problem-Solving Concepts? Problem-solving is an important skill at both the personal and professional levels. People make decisions to solve a problem. Whether you’re fixing a leaking faucet at home or troubleshooting complex technical issues on a computer, the ability to effectively troubleshoot challenges is invaluable. In this comprehensive tutorial, we’ll delve into the troubleshooting mindset, general availability, and its practical applications in the computer industry. By breaking down the process into manageable steps and providing technical examples, we aim to equip readers with the tools to solve problems practically and confidently. Total Steps for Problem Solving: 1. Identifying the Problem The fundamental principle of problem-solving lies in accurately identifying the issue at hand. This involves understanding the signs and figuring out what's causing the problem. Consider a scenario where your computer suddenly c...