Errno (Error Report) in C language usage
There are three forms of error reporting in the C language standard library.
1,Errno
Errno The header file is defined as follows:
#ifndef errnoextern int errno;#endif
The external variable errno stores the implementation-defined error codes in the library program. It is usually defined as a macro starting with E in errno. h,
All error codes are positive integers.
# define EDOM 33 /* Math argument out of domain of function. */
The EDOM means that the parameter is not in the accepted domain of the mathematical function. This macro is used in the example later.
A common usage of errno is to reset the value before calling the library function, and then check the value.
2,Strerror
Strerror in Is defined as follows:
__BEGIN_NAMESPACE_STD/* Return a string describing the meaning of the `errno' code in ERRNUM. */extern char *strerror (int __errnum) __THROW;__END_NAMESPACE_STD
The strerror function returns a pointer to an error message string. Its content is defined by the implementation. The string cannot be modified, but it can be overwritten when the strerror function is called later.
3,Perror
Perror in Is defined as follows:
__BEGIN_NAMESPACE_STD/* Print a message describing the meaning of the value of errno. This function is a possible cancellation point and therefore not marked with __THROW. */extern void perror (const char *__s);__END_NAMESPACE_STD
The perror function prints the following sequence in the standard error output stream: parameter string s, colon, space, Error Short Message and line feed containing the current error code in errno. In the standard C language, if s is a NULL pointer or a NULL Character pointer, only the short message of the error is printed, and the preceding parameter string s, colon, and space are not printed.
Below are a few simple examples
#include
#include
#include
#include
int main(void){ errno = 0; int s = sqrt(-1); if (errno) { printf("errno = %d\n", errno); // errno = 33 perror("sqrt failed"); // sqrt failed: Numerical argument out of domain printf("error: %s\n", strerror(errno)); // error: Numerical argument out of domain } return 0;}