C Programming Tutorial 0/65 lessons ~6 min read Lesson 42

    Basics of File Handling

    File handling in C uses FILE pointers — fopen to open, fclose to close, and fprintf/fscanf or fread/fwrite for data.

    Course progress0%
    Focus
    10 guided sections
    Practice signal
    Examples included
    Career prep
    Foundation builder

    Introduction

    File handling in C uses FILE pointers — fopen to open, fclose to close, and fprintf/fscanf or fread/fwrite for data.

    Understanding the topic

    Open modes r read, w write, a append, rb/wb binary.

    Always check fopen returns NULL on failure.

    Close files fclose flushes buffers and releases handle.

    • Open modes — r read, w write, a append, rb/wb binary.
    • Always check — fopen returns NULL on failure.
    • Close files — fclose flushes buffers and releases handle.

    Step-by-step explanation

    1. Open modes — r read, w write, a append, rb/wb binary.
    2. Always check — fopen returns NULL on failure.
    3. Close files — fclose flushes buffers and releases handle.

    Syntax reference

    Syntax reference:

    c
    FILE *f = fopen("path", "mode");

    Informative example

    Example program:

    c
    #include <stdio.h>
    int main(void) {
    FILE *f = fopen("demo.txt", "w");
    if (!f) return 1;
    fprintf(f, "Hello file\n");
    fclose(f);
    return 0;
    }

    Execution workflow

    1Basics of File Handling — step by step
    1 / 3

    Open modes

    r read, w write, a append, rb/wb binary.

    Best practices

    • Enable warnings: gcc -Wall -Wextra -std=c11 source.c -o app
    • Give every variable a defined value before it is read.
    • Stay inside array bounds — C will not stop you from over-running a buffer.

    Common mistakes

    • Reading uninitialized storage — behavior is undefined.
    • Dismissing compiler warnings instead of fixing root causes.
    • Ignoring NULL returns from malloc, fopen, and similar APIs.

    Hands-on exercise

    Practice problems:

    • Write integers to a file
    • Read them back

    Summary

    Basics of File Handling in C — FILE streams, open modes, and fclose discipline.

    Ready to mark this lesson complete?Track your journey across the entire course.