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

err is integer errno code; out receives formatted string with capacity cap.

Starter code

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

Common mistakes

Using sprintf without bounds checking or ignoring truncation.

Edge cases to handle

Unknown errno value, cap too small for full message.

Complexity

O(1).

Background lessons

Up next

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