Print errno as mnemonic?

The second part of your question is answered by strerror (as you point out), or better strerror_r, but in glibc at least you can simply use %m as a format specifier.

The first part is more interesting, i.e. how do you get the name of the C constant for the error. I believe there is no way to do that using standard glibc. You could construct your own static array or hash table to do this relatively easily.


Unfortunately not; there is no introspection support for the E error macros.

You can do this trivially in Python:

import errno
print(errno.errorcode[errno.EPERM])

This is because the Python maintainers have gone to the trouble of generating a lookup table: http://hg.python.org/cpython/file/tip/Modules/errnomodule.c


What's the problem?

perl -ne 'print "$1\n" if /^#\s*define\s+(E[A-Z0-9]+)/' < /usr/include/sys/errno.h | sort | uniq | perl -ne 'chomp; print "    { $_, \"$_\" }\n"'

This unix shell command printa out E* defines from /usr/include/sys/errno.h (where actual defines live) in form { EINVAL, "EINVAL" },. You may then wrap it into an array:

struct errno_str_t {
    int code;
    const char *str;
} errnos[] = {
    { EINVAL, "EINVAL" },
    ...
};

And sort by errno value at runtime if needed. If you want to be portable (to some extent), consider making this a part of build process. Do not worry, that's the true unix way of doing this :)

Tags:

Linux

C