Using errno in C
Introduction to errno in C
In C, the standard library maintains a global variable called errno
, which is used by many functions to report the error details when they fail. It is an integer type variable and is included in the errno.h
header file.
What is errno?
errno
is a pre-defined variable in C, declared in the header file errno.h
. When system calls and some library functions encounter an error, they usually do not return the error code directly. Instead, they set the variable errno
to a value corresponding to the error that occurred. This value can then be used to generate a more detailed error message or handle the error appropriately.
How to use errno?
Let's look at an example of how to use errno
.
#include <stdio.h>
#include <errno.h>
int main(){
FILE *f;
f = fopen("non_existent_file.txt", "r");
if(f == NULL) {
printf("Error number: %d\n", errno);
perror("Error");
return 1;
}
fclose(f);
return 0;
}
In this example, we try to open a file that does not exist. When fopen()
fails to open the file, it returns NULL
and sets the errno
variable to a value representing the error. We then print this error number and use the perror()
function to print a human-readable error message.
Functions associated with errno
There are two main functions associated with errno
: perror()
and strerror()
.
perror()
The perror()
function takes a string argument, adds a colon and a space, prints the string followed by an error message based on the current value of errno
, and then ends with a newline.
perror("An error occurred");
strerror()
The strerror()
function returns a pointer to a string that describes the error code passed in the argument errno.
printf("Error: %s\n", strerror(errno));
Resetting errno
It is important to note that errno
is not automatically set to zero at the start of a program. It only gets set by a function when an error occurs. Therefore, it is good practice to set errno
to zero before calling a function that may set it, to avoid confusion with previous errors.
errno = 0;
Conclusion
Understanding and using errno
properly is a key aspect of error handling in C. By checking the value of errno
after a function call, you can determine whether an error occurred and take appropriate action.
Remember that errno
does not get reset between function calls unless you do it explicitly, so always set errno
to zero before calling a function that might change its value.
It is also important to note that errno
is not thread-safe, so in a multi-threaded program, a function call in one thread could overwrite the value set by a function call in another thread. In such cases, you should use thread-local error numbers provided by some APIs or protect access to errno
with a mutex.