C errno
Created By: chatGPT
C's errno is a global variable typically used for error reporting in C programs. When a function fails, it often sets this variable to a specific error code that can be checked later. The errors are defined in the header file
<errno.h>
. Common error values include ENOMEM
, EINVAL
, and EPERM
, among others. You should always check the value of errno after a function call that can potentially fail, but remember to reset it to 0
before making the call if you need to distinguish between errors or success later.#include <stdio.h>
#include <errno.h>
#include <string.h>
int main() {
FILE *file = fopen("non_existent.txt", "r");
if (file == NULL) {
// Print the error message corresponding to errno
printf("Error opening file: %s\n", strerror(errno));
}
return 0;
}
errno is set to
0
at the start of the program, and it is essential to reset it before checking after function calls, as it retains the last error code encountered during the program's runtime. This variable is particularly useful for determining the reason behind a failure, thus aiding in debugging and error handling.#include <stdio.h>
#include <errno.h>
#include <string.h>
int main() {
errno = 0; // Reset errno before the call
// Attempt to open a non-existent file
FILE *file = fopen("another_non_existent.txt", "r");
if (file == NULL) {
if (errno != 0) {
printf("Error opening file: %s\n", strerror(errno));
}
}
return 0;
}
In addition to using strerror() for converting error numbers to strings, you might also utilize perror() for error messages. perror() automatically prints a description of the last error that occurred, along with the string you provide.
#include <stdio.h>
#include <errno.h>
int main() {
FILE *file = fopen("missing.txt", "r");
if (file == NULL) {
perror("Failed to open file"); // Outputs the error message
}
return 0;
}
It's crucial to remember that errno is not a function, it's a variable. Operations that fail will leave the errno variable unchanged if the function is successful. Thus, you should always check if errno has been set after calling a function that can fail.
#include <stdio.h>
#include <errno.h>
int main() {
int result = some_function();
if (result == -1) { // Assuming -1 indicates failure
// Check errno
if (errno) {
// Handle error
printf("Error code: %d\n", errno);
}
}
return 0;
}