Skip to main content

Lesson 4 of 5

errno, perror & strerror - Robust Error Handling

When a C library function fails, it typically returns `-1` or `NULL` and sets the global `errno` variable to an error code defined in `<errno.h>`. `perror(str)` prints `str: <error message>` to stderr. `strerror(errno)` returns the error message as a string. Reading `errno` is only meaningful immediately after a failed call - subsequent calls may overwrite it.

10 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

errno-Based Error Handling - Production Pattern

errno-Based Error Handling - Production Pattern
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>

/* ── errno codes (partial list) ─────────────────────────────
   ENOENT  = 2  (No such file or directory)
   EACCES  = 13 (Permission denied)
   ENOMEM  = 12 (Out of memory)
   EINVAL  = 22 (Invalid argument)
   EEXIST  = 17 (File exists)
   EIO     =  5 (I/O error)
   ENOSPC  = 28 (No space left on device)                      */

int safe_open_read(const char *path, FILE **out) {
    errno = 0;   /* clear errno before the call */
    FILE *fp = fopen(path, "r");
    if (fp == NULL) {
        int saved_err = errno;   /* save immediately - next call may change it */
        fprintf(stderr, "Cannot open '%s': %s (errno=%d)
",
                path, strerror(saved_err), saved_err);
        return saved_err;        /* return specific error code */
    }
    *out = fp;
    return 0;
}

long read_file_to_buffer(const char *path, char **buf_out) {
    FILE *fp;
    int rc = safe_open_read(path, &fp);
    if (rc != 0) return -1;

    /* Get size */
    fseek(fp, 0, SEEK_END);
    long size = ftell(fp);
    if (size < 0) { perror("ftell"); fclose(fp); return -1; }
    rewind(fp);

    char *buf = malloc((size_t)size + 1);
    if (!buf) {
        fprintf(stderr, "malloc(%ld): %s
", size, strerror(ENOMEM));
        fclose(fp); return -1;
    }

    size_t n = fread(buf, 1, (size_t)size, fp);
    if (ferror(fp)) {
        perror("fread");
        free(buf); fclose(fp); return -1;
    }
    buf[n] = '';
    fclose(fp);
    *buf_out = buf;
    return (long)n;
}

int main(void) {
    /* Test nonexistent file */
    FILE *fp;
    safe_open_read("/nonexistent/path.txt", &fp);

    /* Test valid read */
    char *content = NULL;
    long bytes = read_file_to_buffer("/etc/hostname", &content);
    if (bytes >= 0 && content) {
        printf("Read %ld bytes from /etc/hostname: %s", bytes, content);
        free(content);
    }

    /* perror - the quick one-liner */
    errno = ENOENT;
    perror("test perror");   /* test perror: No such file or directory */

    return 0;
}

Common Mistakes

  • Reading `errno` after another function call - `fopen` fails, then `printf` resets `errno`. Always save `errno` to a local variable immediately after a failure: `int saved_err = errno;`.
  • Using `perror` when the error message needs the filename - `perror("fopen")` prints 'fopen: No such file or directory' without telling you WHICH file. Use `fprintf(stderr, "cannot open '%s': %s\n", path, strerror(errno))` for context.
  • `strerror` is not thread-safe on all platforms - use `strerror_r` (POSIX) or Windows's `strerror_s` in multi-threaded code.

Tip

Tip

Practice errno perror strerror Robust Error Handling in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

System calls set errno on failure; perror and strerror provide human-readable diagnostic messages

Practice Task

Note

Practice Task - (1) Write a working example of errno perror strerror Robust Error Handling 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 errno perror strerror Robust Error Handling 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

  • When a C library function fails, it typically returns `-1` or `NULL` and sets the global `errno` variable to an error code defined in `<errno.
  • Reading `errno` after another function call - `fopen` fails, then `printf` resets `errno`. Always save `errno` to a local variable immediately after a failure: `int saved_err = errno;`.
  • Using `perror` when the error message needs the filename - `perror("fopen")` prints 'fopen: No such file or directory' without telling you WHICH file. Use `fprintf(stderr, "cannot open '%s': %s\n", path, strerror(errno))` for context.
  • `strerror` is not thread-safe on all platforms - use `strerror_r` (POSIX) or Windows's `strerror_s` in multi-threaded code.

Topics in This Module

0/5 done