The perror function prints error messages to the stderr stream based on the error state in the errno.
Basic Usage
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.
Return Value
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
Perror Example
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:
Conclusion
This quick tutorial discussed how to use the perror function to get descriptive error messages encountered in the program.