linux-sysprog · intermediate · ~20 min
snprintf-based safe concatenation with the per-segment slash rule.
Implement int path_join(char *out, size_t cap, const char *a, const char *b).
The function concatenates two path components into out, inserting a single / between them if needed (no double slashes, no missing separators).
b starts with /, treat it as absolute — out is just a copy of b (capped).a is empty, out is just a copy of b.b is empty, out is just a copy of a.out is a + '/' + b, with at most one / between them.Return:
0 on success.-1 if out is too small.path_join(out, 32, "/etc", "passwd") -> 0, out = "/etc/passwd"
path_join(out, 32, "/etc/", "passwd") -> 0, out = "/etc/passwd" // no double slash
path_join(out, 32, "/etc", "/passwd") -> 0, out = "/passwd" // b absolute
path_join(out, 32, "", "passwd") -> 0, out = "passwd"
path_join(out, 5, "/etc", "passwd") -> -1 // too small
Every CLI tool that constructs dir/file does some version of this. Doing it without snprintf overflows or double slashes is the kind of small care that distinguishes solid C from sloppy.
Two path components + output buffer.
0/-1 + populated out.
Use snprintf for the safe build; reject on cap overflow.
#include <stddef.h>
int path_join(char *out, size_t cap, const char *a, const char *b) { /* TODO */ return -1; }
Always inserting / (creates // when a already ends with /). Forgetting the absolute-b rule. Failing to detect snprintf truncation.
Both empty; a ending in /; b starting with /; tiny cap.
O(strlen(a) + strlen(b)).
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.