strerror
- C course
- Intermediate
- Lesson 55/116
- 5 min
Learn to get error messages with strerror.
The strerror function
strerror converts an errno code to a human-readable string. Usage: char *msg = strerror(errno);. You print the returned string with printf("%s\n", msg);. You need <string.h>.
perror combines your prefix with the message and writes to stderr; strerror returns just the message. So strerror is more flexible: you can write it to a file, log it or concatenate with another string. You choose the output stream.
strerror and fprintf
You can write strerror's string to stderr with fprintf(stderr, "error: %s\n", strerror(errno));. This works like perror but you fully control the format.
The string strerror returns lives in static memory; don't free it. A later strerror call in the same thread overwrites this buffer. So use the string at once or copy it with strncpy. In multi-threaded programs prefer strerror_r, the thread-safe version.
Practice Print an error with strerror
Include <stdio.h> and <string.h>. In main, assign errno = ENOENT;, then get the message with char *msg = strerror(errno); and print it with printf("%s\n", msg);. The typical output for ENOENT is No such file or directory.
Starter code
#include <stdio.h>
// Include string.h
int main(void) {
// Set errno to ENOENT
// Get the message with strerror
// Print msg
return 0;
}Sample solution
#include <stdio.h>
#include <string.h>
int main(void) {
errno = ENOENT;
char *msg = strerror(errno);
printf("%s\n", msg);
return 0;
}Expected output
No such file or directory
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match perror vs strerror
| Term | Meaning |
|---|---|
perror |
Writes to stderr |
strerror |
Returns a string |
Prefix |
perror parameter |
Flexibility |
strerror advantage |
2 Complete the strerror call
char *msg = ____(errno);
printf("%s\n", msg);
char *msg = strerror(errno);
printf("%s\n", msg);
Explanation: strerror(errno) returns the error string.
3 What does strerror(errno) return?
- char * string Correct answer
- FILE * stream
- void
- int error code
Explanation: strerror returns the error string as char *.