File Handling in C

    Atul Kabra3 min readUpdated

    File handling in C lets your program read from and write to files on disk, so data survives after the program ends. The workflow is always the same three steps: open a file with fopen, read or write it, and close it with fclose. Everything goes through a FILE * — a pointer to a file stream.

    Opening a file

    fopen takes a filename and a mode, and returns a FILE *. If it fails (file missing, no permission), it returns NULL — always check:

    FILE *fp = fopen("data.txt", "r");   /* "r" = open for reading */
    if (fp == NULL) {
        printf("Could not open file.\n");
        return 1;
    }
    

    Common modes:

    ModeMeaning
    "r"read (file must exist)
    "w"write (creates or erases existing)
    "a"append (adds to the end)
    "r+"read and write

    Add b (e.g. "rb") for binary files; text mode is the default.

    Writing to a file

    Use fprintf exactly like printf, but with the file pointer as the first argument:

    #include <stdio.h>
    
    int main(void) {
        FILE *fp = fopen("notes.txt", "w");   /* create/overwrite */
        if (fp == NULL) {
            printf("Open failed.\n");
            return 1;
        }
    
        fprintf(fp, "Hello from Jalgaon\n");   /* write a line */
        fprintf(fp, "Line 2: %d\n", 42);       /* formatting works too */
    
        fclose(fp);   /* ALWAYS close: flushes data and frees the handle */
        return 0;
    }
    

    "w" mode erases any existing content, so use "a" if you want to keep adding.

    Reading from a file

    fgets reads one line at a time and is the safe choice for text. Loop until it returns NULL (end of file):

    #include <stdio.h>
    
    int main(void) {
        FILE *fp = fopen("notes.txt", "r");
        if (fp == NULL) {
            printf("Open failed.\n");
            return 1;
        }
    
        char line[256];
        while (fgets(line, sizeof(line), fp) != NULL) {  /* read line by line */
            printf("%s", line);   /* fgets keeps the newline, so no extra \n */
        }
    
        fclose(fp);
        return 0;
    }
    

    Want to learn this properly?

    Join the waitlist for C Programming — beginner-friendly, project-first classes in Jalgaon.

    Explore C Programming

    Why fclose matters

    Closing a file flushes any buffered data to disk and releases the operating system handle. Forgetting fclose can lose the last writes or leak resources. Close every file you open.

    Appending instead of overwriting

    When you want to keep a file's existing contents and add to the end — a log file, for example — open it in append mode "a":

    #include <stdio.h>
    
    int main(void) {
        FILE *fp = fopen("log.txt", "a");   /* "a" preserves existing lines */
        if (fp == NULL) {
            return 1;
        }
        fprintf(fp, "New entry\n");   /* added at the end, old lines kept */
        fclose(fp);
        return 0;
    }
    

    Run this a few times and you'll see the file grow rather than reset — the key difference between "a" and "w".

    Other useful functions

    • fscanf — formatted reading (like scanf from a file). Use carefully; fgets is safer for whole lines.
    • fputc / fgetc — write/read a single character.
    • feof / ferror — check end-of-file and error states.
    • rewind — move the read/write position back to the start of the file.

    Common mistakes

    • Not checking fopen for NULL — then using a bad pointer crashes the program.
    • Forgetting fclose — buffered writes may never reach the disk.
    • Using "w" when you meant "a""w" silently erases the file.
    • Reading past end of file without checking the return value of fgets/fscanf.
    • Buffer too small for fgets — long lines get split; size your buffer generously.

    FAQ

    Where is the file created? In the program's current working directory unless you give a full path.

    Text vs binary mode — which do I use? Text mode ("r", "w") for human-readable files. Binary ("rb", "wb") for raw data like images or structs.

    Continue at the hub C Programming, then Strings in C and Pointers in C.

    Want to learn this properly? Join the waitlist for our C Programming course — taught in Jalgaon.

    Want to learn this properly?

    Join the waitlist for C Programming — beginner-friendly, project-first classes in Jalgaon.

    Explore C Programming
    Atul Kabra

    Founder, Infoplanet

    Atul Kabra founded Infoplanet in 2001 and has spent over two decades teaching programming — C, C++, Java, databases and more — to students across Maharashtra.

    Related guides