file-handling · intermediate · ~15 min
Quote-aware CSV field splitting.
Pull one field out of a CSV line, correctly handling double-quoted fields that contain commas — the part naive splitters get wrong.
Implement int csv_field(const char *line, int idx, char *out, size_t cap) that copies the 0-based field number idx from line into out (NUL-terminated, bounded by cap). If a field is wrapped in double quotes, the surrounding quotes are stripped and any commas inside them are kept as part of the field.
line: one CSV row (NUL-terminated, no trailing newline needed).idx: 0-based field index to extract.out / cap: destination buffer and its size.Return the length of the extracted field (bytes written to out, excluding the NUL). Return -1 if line/out is NULL, idx is out of range, or the field doesn't fit in cap.
csv_field("a,b,c", 1, out, 64) -> 1, out = "b"
csv_field("x,\"hello, world\",z", 1, out, 64) -> 12, out = "hello, world"
csv_field("a,b,c", 5, out, 64) -> -1 (idx past last field)
idx beyond the last field, or a field too big for cap: -1.in_quotes flag; only an unquoted comma ends a field. Bound every write by cap.Real CSV has quoted fields containing commas — a naive split breaks on them. Getting this right is the heart of CSV handling.
line: one CSV row. idx: 0-based field number. out/cap: result buffer and size.
int length of the field copied to out, or -1 on NULL / out-of-range / overflow.
Quote-aware: commas inside double quotes are literal; strip surrounding quotes.
#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.