errno helps you find out what went wrong when a C function fails. It stores error codes so you can understand and fix problems.
0
0
Using errno in C
Introduction
When a function like fopen fails to open a file and you want to know why.
When a system call returns an error and you need the error reason.
When debugging your program to see what caused a failure.
When you want to show a helpful error message to the user.
When handling errors in functions that set errno on failure.
Syntax
C
#include <errno.h> #include <stdio.h> #include <string.h> // errno is a global variable // Use perror() or strerror(errno) to print error messages
errno is set by system and library calls when an error happens.
Do not change errno yourself; just read it after a failure.
Examples
This example tries to open a file that does not exist and prints the error message using strerror(errno).
C
#include <errno.h> #include <stdio.h> #include <string.h> int main() { FILE *f = fopen("missing.txt", "r"); if (!f) { printf("Error opening file: %s\n", strerror(errno)); } return 0; }
Here, perror prints a message with the error description automatically.
C
#include <errno.h> #include <stdio.h> int main() { FILE *f = fopen("missing.txt", "r"); if (!f) { perror("fopen failed"); } return 0; }
Sample Program
This program tries to open a file that does not exist. It then prints the numeric error code, the error message string, and uses perror to show the error.
C
#include <errno.h> #include <stdio.h> #include <string.h> int main() { FILE *file = fopen("nonexistent.txt", "r"); if (!file) { printf("Failed to open file. errno = %d\n", errno); printf("Error message: %s\n", strerror(errno)); perror("perror output"); return 1; } fclose(file); return 0; }
OutputSuccess
Important Notes
errno is only valid right after a function fails; calling other functions may change it.
Always check the function's return value before using errno.
Different systems may have different error codes, but common ones like ENOENT (file not found) are standard.
Summary
errno stores error codes set by failed functions.
Use strerror(errno) or perror() to get readable error messages.
Check function results before reading errno.