file-handling · intermediate · ~15 min

Extract the Nth CSV field

Quote-aware CSV field splitting.

Challenge

Pull one field out of a CSV line, correctly handling double-quoted fields that contain commas — the part naive splitters get wrong.

Task

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.

Input

  • line: one CSV row (NUL-terminated, no trailing newline needed).
  • idx: 0-based field index to extract.
  • out / cap: destination buffer and its size.

Output

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.

Example

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)

Edge cases

  • Quoted field containing a comma: keep the comma, drop the quotes.
  • First or last field.
  • idx beyond the last field, or a field too big for cap: -1.

Rules

  • Track an in_quotes flag; only an unquoted comma ends a field. Bound every write by cap.

Why this matters

Real CSV has quoted fields containing commas — a naive split breaks on them. Getting this right is the heart of CSV handling.

Input format

line: one CSV row. idx: 0-based field number. out/cap: result buffer and size.

Output format

int length of the field copied to out, or -1 on NULL / out-of-range / overflow.

Constraints

Quote-aware: commas inside double quotes are literal; strip surrounding quotes.

Starter code

#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;
}

Common mistakes

Splitting on every comma (breaks quoted fields). Not stripping the surrounding quotes. No overflow guard.

Edge cases to handle

Quoted field with an internal comma. First/last field. idx beyond the row.

Complexity

O(line length).

Background lessons

Up next

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