The perror function prints error messages to the stderr stream based on the error state in the errno.
The syntax for the perror function is:
The perror function accepts one parameter as a pointer to a null-terminated string which contains a descriptive message about the error.
HINT: The errno refers to a system variable that stores an error code describing an error condition produced by a call to a library function.
REFERENCE: The Linux Manual:
The <errno.h> header file defines the integer variable errno set by system calls and some library functions in the event of an error to indicate what went wrong.
The perror function has a void return type, an error message formed by combining the following—in order.
- The value of the string pointer passed to the function (str).
- A colon (:)
- A complete error message describing the error code in errno.
A new line character \n
We can illustrate the working of the perror by simply opening a non-existent file. The example code for that is:
Once we run the above code, we should get the following example output:
You can download the PDF below to know the error numbers and their meanings.
This quick tutorial discussed how to use the perror function to get descriptive error messages encountered in the program.