linux-sysprog · beginner · ~10 min

Translate an errno value into a friendly string

Compose `strerror` + `snprintf` with a cap.

Challenge

Turn a raw errno code into a readable message that pairs the number with its strerror text.

Task

Implement void describe_errno(int err, char *out, size_t cap) that formats err into out.

Input

  • err: an errno value.
  • out, cap: destination buffer and its size.

Output

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.

Example

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

Edge cases

  • err == 0 typically maps to "Success".
  • An unknown errno value yields strerror's "Unknown error N" text.
  • A small cap truncates safely (no overflow).

Why this matters

A user-facing error message that says 'errno=2' is useless. Every defensive tool wraps strerror into something readable.

Input format

An errno value err, plus an output buffer out of size cap.

Output format

Writes 'errno= (<strerror(err)>)' into out (NUL-terminated, capped at cap).

Constraints

Use snprintf with the format "errno=%d (%s)". Always stay within cap.

Starter code

#include <stddef.h>
void describe_errno(int err, char *out, size_t cap) { /* TODO */ }

Common mistakes

Calling strerror without a cap.

Edge cases to handle

errno == 0 ("Success"); unknown errno value (strerror returns "Unknown error N").

Complexity

O(1).

Background lessons

Up next

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.