Error numbers in C language refer to the list of constant integer values or error codes defined by the ISO C, POSIX, and the C++ standard libraries. The error codes represent different types of errors. When a function fails in C, it returns -1
or NULL
, and the global variable errno
(defined in the errno.h
header file) is set to the respective error code.
Below is a table showing a sample list of error codes and their respective meaning in the Linux operating system:
Errno value | Error code | Meaning |
2 | ENOENT | No such file or directory |
5 | EIO | I/O error |
7 | E2BIG | Argument list too long |
11 | EAGAIN | Try again |
33 | EDOM | Math argument out of domain of func |
34 | ERANGE | Math result not representable |
84 | EILSEQ | Illegal byte sequence |
Error handling in C can be done by tracking the value of errno
after each function call. The errno.h
header file also provides functions such as perror()
and strerror()
to display the error message corresponding to the errno
value. The function declarations are as follows:
void perror(const char *s);
s
: custom error message
Output: custom error message followed by colon, space, and implementation-defined error message
char* strerror(int errnum);
errnum
: error code
Output: pointer to the implementation-defined error message string
#include <stdio.h>#include <errno.h>#include <string.h>#include <math.h>int main(){FILE * fp;fp = fopen("file.txt", "r");printf("1. Opening a file which does not exist \n");printf("errno value: %d\n", errno);printf("%s \n", strerror(errno));perror("Error message is");double a = log(-10);printf("\n2. Taking log of negative value \n");printf("errno value: %d\n", errno);printf("%s \n", strerror(errno));perror("Error message is");double b = log(0.0);printf("\n3. Taking log of zero \n");printf("errno value: %d\n", errno);printf("%s \n", strerror(errno));perror("Error message is");return 0;}
In the above program, we see three types of errors with their corresponding errno
values and implementation-defined error messages using perror()
and strerror()
.
In line 9, fopen()
raises an error because the file does not exist, and therefore errno
is set to 2
In line 16, log(-10)
results in , and therefore errno
is set to 33
In line 22, log(0.0)
results in , and therefore errno
is set to 34