Skip to main content
Brave Programmer Logo

BraveProgrammer

BraveProgrammer

HomeProjectsBlogsCoursesLessonsAbout

Site footer

BraveProgrammer

Free coding courses, practical tutorials, and real projects from BraveProgrammer. Learn web development with React, Next.js, and TypeScript.

Navigation

  • Home
  • Projects
  • Blogs
  • Courses

Resources

  • About
  • Lessons

© 2026 BraveProgrammer. All rights reserved.

  1. Courses
  2. /
  3. C Programming Fundamentals

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;
}
Previous: File I/O – Binary FilesNext: Debugging with GDB