Lesson 44 of 50 · c
Error Handling – `errno` & `perror`
Duration: 8 mins
errno (declared in <errno.h>) holds the error code from the last library call that set it. Functions like strerror translate it to a readable string.
FILE *fp = fopen("missing.txt", "r");
if (!fp) {
perror("fopen"); // prints: fopen: No such file or directory
// errno now contains ENOENT
}
Never rely on errno after a successful call — only check it when a function signals an error (often returns -1 or NULL).
📚 Example: Using strerror
#include <stdio.h>
#include <errno.h>
#include <string.h>
int main(void) {
FILE *f = fopen("/root/secret", "r");
if (!f) {
printf("Error (%d): %s\n", errno, strerror(errno));
}
return 0;
}