How to Use errno in C: Simple Guide with Examples
In C,
errno is a global variable set by system calls and library functions when an error occurs. To use it, include <errno.h>, check if a function signals an error, then read errno to find the error code and use perror() or strerror() to get a readable message.Syntax
errno is a global integer variable defined in <errno.h>. It is set by system calls and some library functions when an error happens. You should check the function's return value first, then read errno if an error is indicated.
Common usage:
- Include
<errno.h> - Call a function that may fail
- If failure detected, read
errno - Use
perror()orstrerror(errno)to print error message
c
#include <errno.h> #include <stdio.h> // Example usage pattern int result = some_function(); if (result == -1) { // check error condition int err = errno; // save errno immediately perror("Error message"); // print error description // or use strerror(err) to get string }
Example
This example tries to open a file that does not exist. When fopen() fails, it sets errno. We print the error message using perror().
c
#include <stdio.h> #include <errno.h> int main() { FILE *file = fopen("nonexistent.txt", "r"); if (file == NULL) { perror("Failed to open file"); return 1; } fclose(file); return 0; }
Output
Failed to open file: No such file or directory
Common Pitfalls
- Not checking function return values:
errnois only meaningful if the function signals an error (like returningNULLor-1). - Using
errnowithout resetting:errnois not cleared automatically, so old errors may remain if you don't reset it before a call. - Reading
errnoafter another function call: Always saveerrnoimmediately after the error, because other calls may change it.
c
#include <stdio.h> #include <errno.h> int main() { errno = 0; // reset errno before call FILE *file = fopen("missing.txt", "r"); if (file == NULL) { int err = errno; // save errno immediately // Some other function call here could change errno perror("Error opening file"); printf("Errno saved: %d\n", err); } return 0; }
Output
Error opening file: No such file or directory
Errno saved: 2
Quick Reference
Remember these key points when using errno:
- Include
<errno.h>to accesserrno. - Check function return values before reading
errno. - Reset
errnoto 0 before calls if you want to detect new errors. - Use
perror()orstrerror(errno)to get readable error messages. - Save
errnoimmediately after an error to avoid overwriting.
Key Takeaways
Always check a function's return value before using errno to detect errors.
Include and use perror() or strerror(errno) to print error messages.
Reset errno to 0 before a call if you want to detect new errors reliably.
Save errno immediately after an error to prevent it from being overwritten.
errno is set only when an error occurs; it is not cleared automatically.