The global errno variable
What you'll learn: How to use the standard library's hidden messenger to find out exactly why a function call failed.
In C, many functions return a simple -1 or NULL when something goes wrong. While this tells you that a failure happened, it doesn't tell you why. Was the file missing? Did you run out of memory? To solve this, the C standard library uses a global variable called errno.
The Doctor’s Clipboard
Imagine you are a doctor at a busy hospital. You ask a nurse to perform a blood test. The nurse returns and simply says, "I couldn't do it." That isn't very helpful. However, if the nurse leaves a note on a shared clipboard in the hallway saying "Patient refused" or "Needle broken," you know exactly how to fix the situation.
In this analogy, errno is the shared clipboard. It is a global integer defined in the <errno.h> header. When a system function hits a snag, it writes a specific error code into errno before returning its failure signal to you.
Seeing errno in Action
To use errno, you must include <errno.h>. Because it is a global variable, its value stays there until another function overwrites it. Therefore, you should always check its value immediately after a function fails.
#include <stdio.h>
#include <errno.h>
#include <string.h>
int main() {
FILE *file = fopen("ghost_file.txt", "r");
if (file == NULL) {
// Something went wrong! Let's check the "clipboard"
printf("Error code: %d\n", errno);
// Use strerror to turn that number into a human message
printf("Meaning: %s\n", strerror(errno));
}
return 0;
}
Important Habits
There are two golden rules when working with errno:
- Check for failure first: Only look at
errnoif the function's return value indicates an error (like returningNULL). If a function succeeds, it doesn't necessarily clearerrno, so you might see a "ghost" error from a previous operation. - Act fast: If you call another library function before reading
errno, that second function might overwrite the error code from the first one.
By reading this hidden variable, your programs move from simply knowing "it didn't work" to understanding the specific reason for the failure.
Key takeaway
The errno variable is a global error code that provides the specific reason for a function's failure, accessible by including <errno.h>.