Course contentsShow
← C
Lesson 740 of 1,21910. Input and OutputFree lesson

Introduction to errno

Introduction to errno

What you'll learn: How to use the global errno variable to identify exactly why a system call or file operation failed.

The Secret Error Code

Imagine you ask a librarian for a book, and they simply say, "I can't get that for you." You’re left wondering: Is the book checked out? Is it lost? Or do I not have permission to enter that section?

In C, functions like fopen behave similarly. When they fail, they often return a generic NULL or -1. To find out the specific reason for the failure, C provides a global variable called errno. When a system-level function hits a snag, it leaves a specific "error code" in this variable, acting like a diagnostic footprint.

How to Check the Footprints

To use it, you must include <errno.h>. When a function fails, errno is updated with an integer representing a specific error. Instead of memorizing numbers, we use built-in constants like ENOENT (File not found) or EACCES (Permission denied).

Because errno is a global variable, its value only tells you about the most recent failure. If you call another function before checking it, the new function might overwrite the old error code!

#include <stdio.h>
#include <errno.h>
#include <string.h>

int main() {
    FILE *fp = fopen("ghost_file.txt", "r");

    if (fp == NULL) {
        // We know it failed, but why?
        printf("Error code: %d\n", errno);

        // strerror turns the number into a human-readable sentence
        printf("Reason: %s\n", strerror(errno));

        if (errno == ENOENT) {
            printf("Action: Please check if the filename is spelled correctly.\n");
        }
    }

    return 0;
}

The "Success" Trap

One important rule: You should only look at errno after a function has already told you it failed (e.g., returned NULL). Most C functions do not reset errno to zero when they succeed. If you check it after a successful call, you might see a "leftover" error from a completely different part of your program, leading to a false alarm.

Key takeaway

Use errno immediately after a failed function call to diagnose the specific cause of the error using standard constants or strerror.