C <string.h> - strerror() Function
The C <string.h> strerror() function interprets the error code errnum and returns a pointer to a null-terminated byte string (C-String) describing the error errnum. The returned message is identical to the description that would be printed by perror().
The returned pointer points to a statically allocated string, which shall not be modified by the program. Further calls to this function may overwrite its content. strerror() is not required to be thread-safe. Implementations may be returning different pointers to static read-only string literals or may be returning the same pointer over and over, pointing at a static buffer in which strerror() places the string.
The error strings produced by strerror() may be specific to each system and library implementation.
Syntax
char* strerror( int errnum );
Parameters
errnum |
Specify the integral value referring to a error code. |
Return Value
Returns a pointer to a null-terminated byte string (C-String) describing error errnum.
Example 1:
The example below shows the usage of strerror() function.
#include <stdio.h> #include <math.h> #include <errno.h> #include <string.h> int main(){ double result = log(0.0); printf("%f\n", result); if (errno == ERANGE) { printf("Value of errno: %d\n", errno); printf("log(0.0) failed: %s\n", strerror(errno)); } }
The output of the above code will be:
-inf Value of errno: 34 log(0.0) failed: Numerical result out of range
Example 2:
The example below the strerror() function is used to describe an error when the input argument is out of domain of a mathematical function.
#include <stdio.h> #include <math.h> #include <errno.h> #include <string.h> int main(){ double result = sqrt(-1.0); printf("%f\n", result); if (errno == EDOM) { printf("Value of errno: %d\n", errno); printf("sqrt(-1.0) failed: %s\n", strerror(errno)); } }
The output of the above code will be:
-nan Value of errno: 33 sqrt(-1.0) failed: Numerical argument out of domain
Example 3:
Consider one more example where this function is used to describe an error when tried to open a file which does not exist.
#include <stdio.h> #include <math.h> #include <errno.h> #include <string.h> int main(){ FILE * pFile; pFile = fopen ("wrongfile.txt", "r"); if (pFile == NULL){ fprintf(stderr, "Value of errno: %d\n", errno); perror("Error printed by perror"); fprintf(stderr, "Error opening file: %s\n", strerror(errno)); } else { fclose (pFile); } }
The output of the above code will be:
Value of errno: 2 Error printed by perror: No such file or directory Error opening file: No such file or directory
❮ C <string.h> Library