C programming - standard library errno.h
The "errno.h" header file in C programming defines the integer variable "errno", which is used to report error conditions that occur during program execution. The value of "errno" is set by certain library functions or system calls when they encounter an error.
When a library function or system call fails, it sets "errno" to a value that represents the type of error that occurred. The "errno" value is typically used to diagnose and recover from errors in the program.
Here are some of the commonly used error codes and their meanings:
- "EINVAL": Invalid argument
- "ENOSPC": No space left on device
- "ENOMEM": Out of memory
- "EBADF": Bad file descriptor
- "EACCES": Permission denied
- "EEXIST": File exists
The "errno" value should only be relied on if a library function or system call reports that it has encountered an error. Otherwise, the value of "errno" is undefined.
Here is an example of using the "errno.h" header file in a C program:
#include <stdio.h> #include <errno.h> int main() { FILE *fp = fopen("nonexistentfile.txt", "r"); if (fp == NULL) { printf("Error opening file: %d\n", errno); } else { // Do something with the file fclose(fp); } return 0; }
In this example, the "fopen" function is used to open a file that does not exist. Since the "fopen" function returns a null pointer to indicate an error, the program checks if "fp" is null. If it is null, the "errno" value is printed to the console to diagnose the error. If "fp" is not null, the program can continue to work with the file.