file-handling · beginner · ~15 min

Safe Bounded CSV Row Parser

Parse comma-delimited records defensively with element and array length limits.

Challenge

CSV line parsing requires bounded extraction of comma-separated tokens without overflowing destination field buffers or exceeding column quotas.

Your Task

Implement:

int parse_csv_line(const char *line, char fields[][32], size_t max_fields);

Rules

  1. If line == NULL, fields == NULL, or max_fields == 0, return -1.
  2. Split line by commas (','). Stop on '\0', '\r', or '\n'.
  3. Each field must fit into 32 bytes (at most 31 characters + NUL). If any field length >= 32, return -1.
  4. If the number of columns exceeds max_fields, return -1.
  5. Empty fields (e.g. "a,,b") produce empty strings ("").
  6. On success, return the number of fields parsed.

Example

char f[4][32];
parse_csv_line("alice,25,admin\n", f, 4); // returns 3: {"alice", "25", "admin"}

Input format

line: input CSV row; fields: 2D array [max_fields][32]; max_fields: size_t capacity.

Output format

Returns field count on success, or -1 on overflow/invalid args.

Constraints

Zero dynamic allocations. Bounded copies with NUL termination.

Starter code

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

Common mistakes

Not handling consecutive commas; copying newline into token; writing past 31 chars.

Edge cases to handle

Empty fields produce empty strings; trailing comma produces empty field; newline terminates row cleanly.

Background lessons

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