Course contentsShow
← C
Lesson 742 of 1,21910. Input and OutputFree lesson

The strerror function

The strerror function

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

Turning numbers into words

Imagine you try to open a locked door. Instead of a voice saying "Access Denied," a tiny screen on the handle simply flashes the number 13. Without a manual, you have no idea what that means. Is the door broken? Is the key wrong?

In C, when a file operation fails (like trying to open a file that doesn't exist), the system doesn't print a friendly warning. Instead, it updates a hidden global variable called errno with a specific number. While errno is great for computers, it’s frustrating for humans. This is where strerror comes in. It acts as your "manual," translating that silent error number into a plain English string you can print to the screen.

How to use it

The strerror function is found in the <string.h> header. It takes one argument—the error number—and returns a pointer to a string describing that error. Usually, we pass it errno (found in <errno.h>) immediately after a function fails.

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

int main() {
    // Attempt to open a file that definitely doesn't exist
    FILE *file = fopen("ghost_file.txt", "r");

    if (file == NULL) {
        // errno was set by the failed fopen call
        // we use strerror to see what actually happened
        printf("Error opening file: %s\n", strerror(errno));
    }

    return 0;
}

If you run this code, instead of seeing "Error 2," you will see:
Error opening file: No such file or directory

Why it matters

Using strerror makes your programs user-friendly and much easier to debug. If a user tries to save a file to a full hard drive or a protected folder, showing them "Permission denied" or "No space left on device" is far more helpful than leaving them to guess why the program crashed. It bridges the gap between the rigid, numeric world of the operating system and the descriptive world of the user.

Key takeaway

Use strerror(errno) to convert numeric error codes into descriptive, human-readable sentences.