The C language provides a global variable errno for program execution. Errno is declared in errno. h.
The following example attempts to open a non-existing file and then outputs the errno value.
# Include <stdio. h>
# Include <stdlib. h>
# Include <fcntl. h>
# Include <unistd. h>
# Include <errno. h>
Int main ()
{
Int FD;
Errno = 0;
FD = open ("XXX", o_rdwr); // assume XXX does not exist
If (errno = 0)
{
Printf ("Open successful/N ");
}
Else
{
Printf ("fail to open, errno is: % d/N", errno );
Exit (1 );
}
Close (FD );
Return 0;
}
Output Error cause
Errno is only an int value. We must look up the table to identify the cause of the Error. To avoid this, we can use the strerror function:
# Include <string. h>
Char * strerror (int err );
Use error as a parameter.
Another function that provides similar functions is perror, which prints an error message based on errno and the input string. Its function prototype is as follows:
# Include <stdio. h>
# Include <errno. h>
Void perror (const char * pszinfo );
The iaoshi parameter of perror is the string to be output. The system automatically connects the string described in the error file mapped using the errno variable to the end of the parameter string. You do not need to add '/N' to the string ', the perror function is automatically added.
The following is an example:
# Include <stdio. h>
# Include <stdlib. h>
# Include <fcntl. h>
# Include <unistd. h>
# Include <errno. h>
# Include <string. h>
Int main ()
{
Int FD;
Errno = 0;
FD = open ("XXX", o_rdwr); // assume XXX does not exist
If (FD =-1)
{
Perror ("fail to open ");
Exit (1 );
}
Close (FD );
Return 0;
}
Output
Fail to open: no such file or directory