Course contentsShow
← C
Lesson 899 of 1,21912. The Standard LibraryFree lesson

Getting error strings with `strerror`

Getting error strings with strerror

What you'll learn: How to translate cryptic numeric error codes into human-readable descriptions using the strerror function.

The Problem with Numbers

When a C function fails—like trying to open a file that doesn't exist—it doesn't send you a text message explaining what went wrong. Instead, the system updates a global hidden variable called errno with a specific number. For example, the number 2 usually means "File not found."

Memorizing hundreds of error codes is impossible for humans, and showing a user "Error 2" is unhelpful. This is where strerror comes in. Think of it as a pocket dictionary that translates a system's numeric error code into a plain English sentence.

Using strerror

The strerror function is defined in <string.h>. It takes an integer (the error number) and returns a pointer to a string describing that error.

#include <stdio.h>
#include <string.h>
#include <errno.h>

int main() {
    // Attempting to open a file that definitely isn't there
    FILE *file = fopen("non_existent_file.txt", "r");

    if (file == NULL) {
        // Save the current error code
        int errNum = errno;

        // Print the numeric code AND the human-readable version
        printf("The system reported error code: %d\n", errNum);
        printf("In plain English: %s\n", strerror(errNum));
    }

    return 0;
}

Why it Matters

Using strerror makes your programs much easier to debug. If a network connection fails or a permission is denied, your program can log "Permission denied" rather than a mysterious "-1" or "13".

One thing to keep in mind: strerror returns a pointer to a static string managed by the C library. You should never try to modify this string or free it. Just read it, print it, or copy it if you need to save it for later, as subsequent calls to strerror might overwrite the buffer in some implementations.

Key takeaway

Use strerror(errno) to turn confusing numeric system errors into readable strings that tell you exactly what went wrong.