file-handling · intermediate · ~15 min
Quote-aware CSV field splitting.
int csv_field(const char *line, int idx, char *out, size_t cap);
Return the 0-based field idx from a CSV line in out (NUL-terminated).
A field may be double-quoted, in which case commas inside the quotes are part
of the field and the surrounding quotes are stripped. Return the field length,
or -1 on NULL, out-of-range idx, or overflow.
"a,b,c", idx 1 → "b""x,\"hello, world\",z", idx 1 → "hello, world"in_quotes flag.out.Real CSV has quoted fields containing commas — a naive split breaks on them. Getting this right is the heart of CSV handling.
#include <stddef.h>
int csv_field(const char *line, int idx, char *out, size_t cap) {
/* TODO */
(void)line; (void)idx; (void)out; (void)cap;
return -1;
}
Splitting on every comma (breaks quoted fields). Not stripping the surrounding quotes. No overflow guard.
Quoted field with an internal comma. First/last field. idx beyond the row.
O(line length).
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.