Skip to main content

Lesson 1 of 5

fopen, fclose & File Modes

`fopen` opens a file and returns a `FILE*` pointer, or `NULL` on failure. **Always check for NULL.** `fclose` flushes the buffer and releases the file descriptor. Forgetting `fclose` causes data loss (for writes) and resource leaks. Understanding the file modes (`r`, `w`, `a`, `rb`, `wb`, etc.) prevents data corruption.

11 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

fopen Modes & Resource Management Patterns

fopen Modes & Resource Management Patterns
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>

int main(void) {
    /* ── fopen modes ──────────────────────────────────────
       "r"  - read text; error if file doesn't exist
       "w"  - write text; CREATES or TRUNCATES file
       "a"  - append text; creates if needed, adds at end
       "r+" - read+write; error if doesn't exist
       "w+" - read+write; creates or truncates
       "rb" - read binary (important on Windows: 
 vs 
)
       "wb" - write binary
       "ab" - append binary                                 */

    /* ── Write a text file ───────────────────────────────── */
    FILE *fp = fopen("test.txt", "w");
    if (fp == NULL) {
        fprintf(stderr, "fopen failed: %s
", strerror(errno));
        return 1;
    }

    fprintf(fp, "Line 1
");
    fprintf(fp, "Value: %d
", 42);
    fprintf(fp, "Pi: %.4f
", 3.14159);

    if (fclose(fp) != 0) {   /* fclose can fail - always check! */
        fprintf(stderr, "fclose failed: %s
", strerror(errno));
        return 1;
    }
    printf("Wrote test.txt
");

    /* ── Read it back ────────────────────────────────────── */
    fp = fopen("test.txt", "r");
    if (fp == NULL) {
        perror("fopen test.txt for reading");  /* perror uses errno */
        return 1;
    }

    char line[256];
    int  lineno = 0;
    while (fgets(line, sizeof(line), fp) != NULL) {
        /* fgets reads up to sizeof(line)-1 chars + null terminates
           Includes the '
' at end of line (if it fits)        */
        line[strcspn(line, "
")] = '';  /* trim trailing newline */
        printf("  [%d] %s
", ++lineno, line);
    }

    if (ferror(fp)) {  /* distinguish EOF from I/O error */
        perror("fgets error");
    }
    fclose(fp);

    /* ── Append to file ──────────────────────────────────── */
    fp = fopen("test.txt", "a");
    if (fp) {
        fprintf(fp, "Appended line
");
        fclose(fp);
    }

    /* ── stdin / stdout / stderr - always open ───────────── */
    /* fprintf(stdout, ...) == printf(...)
       fprintf(stderr, ...) - errors to stderr (unbuffered)
       fscanf(stdin, ...)   == scanf(...)                   */

    return 0;
}

Common Mistakes

  • Not checking `fopen` return value - `fopen` returns `NULL` if the file doesn't exist (mode `r`), permissions denied, or disk full. Every `fopen` must be followed by a NULL check.
  • Using `fclose` on a NULL pointer - if `fopen` fails and you `fclose(NULL)`, it's undefined behaviour. Only call `fclose` on a valid non-NULL `FILE*`.
  • Not distinguishing EOF from read error - both `fgets` and `fread` return NULL/0 at EOF and on error. Use `ferror(fp)` to check for error; `feof(fp)` for end-of-file after the read loop.

Tip

Tip

Practice fopen fclose File Modes in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

fopen opens a buffered stream; checking for NULL and calling fclose prevents descriptor leaks

Practice Task

Note

Practice Task - (1) Write a working example of fopen fclose File Modes from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Quick Quiz

Common Mistake

Warning

A common mistake with fopen fclose File Modes is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready c code.

Key Takeaways

  • `fopen` opens a file and returns a `FILE*` pointer, or `NULL` on failure.
  • Not checking `fopen` return value - `fopen` returns `NULL` if the file doesn't exist (mode `r`), permissions denied, or disk full. Every `fopen` must be followed by a NULL check.
  • Using `fclose` on a NULL pointer - if `fopen` fails and you `fclose(NULL)`, it's undefined behaviour. Only call `fclose` on a valid non-NULL `FILE*`.
  • Not distinguishing EOF from read error - both `fgets` and `fread` return NULL/0 at EOF and on error. Use `ferror(fp)` to check for error; `feof(fp)` for end-of-file after the read loop.

Finished this lesson?

0 of 5 in Module 8
Sign in to save progress

Topics in This Module

0/5 done