linux-sysprog · beginner · ~10 min
Compose `strerror` + `snprintf` with a cap.
Turn a raw errno code into a readable message that pairs the number with its strerror text.
Implement void describe_errno(int err, char *out, size_t cap) that formats err into out.
err: an errno value.out, cap: destination buffer and its size.Writes the string "errno=<err> (<message>)" into out, where <message> is strerror(err). Uses snprintf semantics, so the result is always NUL-terminated and never overruns cap.
describe_errno(2, out, 128) -> out = "errno=2 (No such file or directory)"
describe_errno(0, out, 128) -> out = "errno=0 (Success)"
describe_errno(2, out, 8) -> out truncated but NUL-terminated within 8 bytes
err == 0 typically maps to "Success".cap truncates safely (no overflow).A user-facing error message that says 'errno=2' is useless. Every defensive tool wraps strerror into something readable.
An errno value err, plus an output buffer out of size cap.
Writes 'errno=
Use snprintf with the format "errno=%d (%s)". Always stay within cap.
#include <stddef.h>
void describe_errno(int err, char *out, size_t cap) { /* TODO */ }
Calling strerror without a cap.
errno == 0 ("Success"); unknown errno value (strerror returns "Unknown error N").
O(1).
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.