strerror() Function
The strerror()
function in C converts an error code into a human-readable error message, providing a clear description of the error condition. This function is widely used for debugging and error handling by displaying system or library error messages in a readable format.
Syntax of strerror()
char *strerror(int errnum);
Parameters
Parameter | Description |
---|---|
errnum | An error code representing a specific error condition. |
Return Value
The function returns a pointer to a statically allocated string that describes the error corresponding to the provided error code.
It is important to note that the returned string is statically allocated and must not be modified by the program. Subsequent calls to strerror()
may overwrite the content of this static buffer, so if you need to preserve the error message, copy it to a separate buffer. Additionally, the exact error messages may vary across different systems and library implementations.
Examples for strerror()
Example 1: Displaying the Description for an Invalid Argument Error Code
This example demonstrates how to use strerror()
to obtain and display the error message for a common error code, typically indicating an invalid argument error.
Program
#include <stdio.h>
#include <string.h>
#include <errno.h>
int main() {
int errorCode = EINVAL; // EINVAL represents an invalid argument error
printf("Error %d: %s\n", errorCode, strerror(errorCode));
return 0;
}
Explanation:
- The program includes the necessary headers for input/output operations, string manipulation, and error definitions.
- An error code (
EINVAL
) is used to represent an invalid argument error. - The
strerror()
function returns a descriptive error message corresponding to the error code. - The error code and its message are printed to the console.
Output:
Error 22: Invalid argument
Example 2: Displaying the Success Message for a Zero Error Code
This example illustrates how strerror()
is used to obtain the message associated with a zero error code, which typically indicates a successful operation.
Program
#include <stdio.h>
#include <string.h>
#include <errno.h>
int main() {
int errorCode = 0; // 0 usually indicates no error or success
printf("Error %d: %s\n", errorCode, strerror(errorCode));
return 0;
}
Explanation:
- The program includes the required headers for input/output, string operations, and error code definitions.
- An error code of
0
is used, which typically corresponds to a success status. - The
strerror()
function returns the error message associated with a zero error code, often “Success”. - The error code and its descriptive message are printed to the console.
Output:
Error 0: Success