File Handling · intermediate · ~12 min

Parsing CSV

Split lines into fields safely.

Lesson

CSV is deceptively simple. A naive strtok(line, ",") works for basic input but breaks on quoted fields, escaped quotes, embedded newlines, and trailing empty fields.

Use a library (e.g., libcsv) for production. For controlled inputs, a hand parser that handles "…,…" quoting is ~50 lines and a great C exercise.

Common mistakes

  • strtok is destructive and not re-entrant — strtok_r is the thread-safe variant.
  • Ignoring CRLF — strip both \r and \n.