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
  • Teach on BraveProgrammer

© 2026 BraveProgrammer. All rights reserved.

Error Handling – `errno` | C Programming Fundamentals lesson | BraveProgrammer
  1. Courses
  2. /
  3. C Programming Fundamentals

Lesson 44 of 50

·c

Error Handling – `errno` & `perror`

8 mins

Course progress88%

What you'll learn

Keep these ideas in mind as you work through the lesson.

4 points
  • `errno` is thread‑local on modern implementations.
  • `perror("msg")` prints `<msg>: <description>` to `stderr`.
  • Clear `errno` with `errno = 0;` before a call if you need to differentiate later errors.
  • Only check `errno` after a function indicates failure.

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
", errno, strerror(errno));
    }
    return 0;
}
Make it stickPractice what you've learned1 quiz · 3 practical tests · Optional activities from C Programming FundamentalsBrowse activities
Previous lessonFile I/O – Binary FilesContinue to lesson 45Debugging with GDBBack to C Programming Fundamentals curriculum