file-handling · intermediate · ~15 min

Extract a CSV field

Walk delimited text to a specific field.

Challenge

Extract one field by index from a simple (unquoted) CSV line.

Task

Implement int csv_get_field(const char *line, int idx, char *out, int outsz) that copies the 0-based field idx from line into out (NUL-terminated, bounded by outsz) and returns its length.

Input

  • line: a CSV row (NUL-terminated, no quoting).
  • idx: 0-based field index to extract.
  • out / outsz: destination buffer and its size.

Output

Return the length of the extracted field, or -1 if idx is out of range.

Example

csv_get_field("a,bb,ccc", 0, out, 16)   ->   1,  out = "a"
csv_get_field("a,bb,ccc", 1, out, 16)   ->   2,  out = "bb"
csv_get_field("a,bb", 5, out, 16)       ->   -1  (no such field)

Edge cases

  • idx beyond the last field: -1.
  • The copy is bounded by outsz (NUL-terminated).

Input format

line: a CSV row (no quoting). idx: 0-based field. out/outsz: buffer and size.

Output format

int field length copied to out, or -1 if idx is out of range.

Constraints

No quoting; bound the copy by outsz.

Starter code

#include <string.h>

int csv_get_field(const char *line, int idx, char *out, int outsz) {
    /* TODO */
    return -1;
}

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