file-handling · beginner · ~15 min
Parse comma-delimited records defensively with element and array length limits.
CSV line parsing requires bounded extraction of comma-separated tokens without overflowing destination field buffers or exceeding column quotas.
Implement:
int parse_csv_line(const char *line, char fields[][32], size_t max_fields);
line == NULL, fields == NULL, or max_fields == 0, return -1.line by commas (','). Stop on '\0', '\r', or '\n'.-1.max_fields, return -1."a,,b") produce empty strings ("").char f[4][32];
parse_csv_line("alice,25,admin\n", f, 4); // returns 3: {"alice", "25", "admin"}
line: input CSV row; fields: 2D array [max_fields][32]; max_fields: size_t capacity.
Returns field count on success, or -1 on overflow/invalid args.
Zero dynamic allocations. Bounded copies with NUL termination.
#include <stddef.h>
int parse_csv_line(const char *line, char fields[][32], size_t max_fields) {
(void)line; (void)fields; (void)max_fields;
return -1;
}
Not handling consecutive commas; copying newline into token; writing past 31 chars.
Empty fields produce empty strings; trailing comma produces empty field; newline terminates row cleanly.
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.