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.
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] = '