Lesson 44 of 50
cError Handling – `errno` & `perror`
8 mins
Course progress88%
What you'll learn
Keep these ideas in mind as you work through the lesson.
Lesson 44 of 50
c8 mins
Keep these ideas in mind as you work through the lesson.
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).
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
", errno, strerror(errno));
}
return 0;
}