Skip to content
systemcoding.dev
Systems Programming

Print Readable Errors with strerror and perror

Turn errno into a readable message with perror and strerror in C on Linux with glibc 2.41, and learn when each one fits.

6 min read
Summarize in AI
Flat illustration of a log with a failing line and a wrench, with the C, Rust and C++ logos.

A number like 13 in an error message helps nobody. A message like open: Permission denied tells the person exactly what to fix. C gives you two standard tools for the conversion, perror and strerror, and they solve slightly different problems. This post shows both on Linux with glibc 2.41 and the POSIX.1-2024 definitions, explains when each is the right choice, and covers the mistakes that turn a helpful message into a misleading one. The functions are specified in the POSIX page for strerror and the page for perror. If errno itself is new to you, the previous post in this cluster, on what errno is, comes first.

perror: the one-line report

perror prints to standard error. You give it a prefix string, and it writes the prefix, a colon, a space, the text for the current errno, and a newline. It is the shortest correct way to report a failed system call in a command-line program.

perror_demo.cc
#include <fcntl.h>
#include <stdio.h>

int main(void)
{
    if (open("/etc/shadow", O_RDONLY) == -1) {
        perror("open /etc/shadow");
        return 1;
    }
    return 0;
}

Run as an ordinary user on Linux, it prints:

Text
open /etc/shadow: Permission denied

Two details matter. The output goes to standard error, so it does not mix with the program's normal output when someone redirects with >. And perror reads the global errno itself, so you must call it before anything else can change errno. A common bug is calling printf("failed\n") first. A successful printf may leave errno alone, but a failed or interrupted one will not, and the message then describes the wrong error.

The prefix is yours to choose, and a good prefix names what the program was trying to do and to which object. A bare perror("error") gives error: No such file or directory, which leaves the reader asking which file. A prefix that includes the path, as above, answers the question without a second look at the code.

strerror: the message as a string

perror always prints to standard error. When you want the text elsewhere, in a log line, in a message to a socket client, or inside a longer sentence, use strerror. It takes an error number and returns a pointer to a string.

strerror_demo.cc
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>

int main(void)
{
    const char *path = "/var/log/missing.log";
    if (open(path, O_RDONLY) == -1) {
        int saved = errno;
        fprintf(stderr, "cannot open %s: %s (errno %d)\n",
                path, strerror(saved), saved);
        return 1;
    }
    return 0;
}
Text
cannot open /var/log/missing.log: No such file or directory (errno 2)

Because the message is built by fprintf, you control the format completely. Saving errno into saved first is a habit worth having, because fprintf is a function call that could, in principle, change errno before strerror(errno) is evaluated. In this example the argument order guarantees strerror runs after saved was copied, so the message is right whatever fprintf does internally.

Choosing between them

SituationUse
A command-line tool reporting a failed call to the userperror
A message with a custom format, or sent to a log or socketstrerror with your own formatting
Code that runs in several threads and builds messagesstrerror_r, covered in a later post
A library that must not write to standard errorstrerror, and return the error to the caller

The last row is a design point. A library that calls perror takes a decision away from the program that uses it. The program may have no standard error, may be a daemon with its own logger, or may want to translate the message. A library should return the failure and let the caller choose how to show it.

The text of an error message

The text is not standardized. POSIX defines the error names (ENOENT, EACCES), but the strings come from the implementation. glibc says No such file or directory, musl says the same for this case but differs for others, and the BSD systems have their own wording. Never compare against message text in code, and never parse it. Use the number for decisions and the string only for display.

The text also depends on the locale. If a program calls setlocale(LC_ALL, "") and the environment selects a language with a translation installed, glibc returns the translated string. That is the right behavior for a message shown to the user, and the wrong behavior for a log file that operators search with grep. Log lines that must be searchable are often kept in the C locale, or include the numeric value alongside the text, as the example above does.

Unknown error numbers

What does strerror return for a number it does not know? The standard says it returns a pointer to a message, and glibc returns a string of the form Unknown error 9999. It does not return NULL, so you never need to check for that, but you should know that the message carries the number, which helps when you see it in the field.

unknown_error.cc
#include <stdio.h>
#include <string.h>

int main(void)
{
    printf("%s\n", strerror(0));
    printf("%s\n", strerror(9999));
    return 0;
}
Text
Success
Unknown error 9999

The first line is a reminder that strerror(0) is a valid call that returns Success. If a program prints Success as an error message, it called perror or strerror when errno was zero, which means it reported a failure that no system call had actually produced. That almost always points to a missing check of the return value: the code assumed the call failed when it did not, or it read a stale errno that happened to be zero. Treat Success appearing in an error message as a bug report from your own program.

The lifetime of the returned string

strerror returns a pointer, and that pointer comes with a warning. The POSIX page says the string may be overwritten by a later call to strerror, and that the function is not required to be thread-safe. In glibc, the strings for known errors are static and never change, so the usual single-threaded use is safe. For unknown numbers, glibc formats the text into a buffer, and that buffer can be shared. Do not hold on to the pointer across other strerror calls, and do not modify it. If you need the text later, copy it with strdup or into your own buffer, and in multi-threaded code use strerror_r, which writes into a buffer you supply. The next posts in this cluster give that function the care it needs, because it has two incompatible versions.

A small helper used across a program

Programs that report many errors benefit from one place that formats them. This helper prints a program name, a formatted prefix and the reason, and it saves and restores errno so it is safe to call from cleanup code.

die.cc
#include <errno.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void die(const char *fmt, ...)
{
    int saved = errno;
    va_list ap;
    va_start(ap, fmt);
    vfprintf(stderr, fmt, ap);
    va_end(ap);
    if (saved != 0)
        fprintf(stderr, ": %s", strerror(saved));
    fputc('\n', stderr);
    exit(1);
}

Calling die("cannot read %s", "/etc/missing.conf") after a failed open prints cannot read /etc/missing.conf: No such file or directory and exits with status 1. The if (saved != 0) test lets the same helper report errors that are not system failures, such as invalid user input, without adding Success to the end of the line.

Share

Keep reading

Flat illustration of two options weighed side by side, with the macOS, Linux and Apple logos.
Kernels

Mach Traps vs BSD System Calls on macOS

Learn how macOS routes one trap instruction to either a Mach trap or a BSD system call, how the number sign and class decide, and why you should call libSystem.

8 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.