file-handling · intermediate · ~15 min
Walk delimited text to a specific field.
Extract one field by index from a simple (unquoted) CSV line.
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.
line: a CSV row (NUL-terminated, no quoting).idx: 0-based field index to extract.out / outsz: destination buffer and its size.Return the length of the extracted field, or -1 if idx is out of range.
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)
idx beyond the last field: -1.outsz (NUL-terminated).line: a CSV row (no quoting). idx: 0-based field. out/outsz: buffer and size.
int field length copied to out, or -1 if idx is out of range.
No quoting; bound the copy by outsz.
#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.