Project: A CSV Parser and Report With Strict Validation
Build a program that parses CSV text with strtok_r and strtod, validates every field and range, reports each bad line with a reason, and prints per-sensor statistics verified against Python.
In this lesson you will
- Parse delimited text safely
- Validate numbers with strtod and endptr
- Report bad lines with reasons
- Verify a report independently
About 28 minutes
The file that someone edited by hand
Bruno exports the logger data as CSV, and a colleague edits it by hand in a spreadsheet. Now the file contains a value of “x”, a line with a missing field, a value with trailing letters and a temperature of minus 80 degrees in a greenhouse. A program that trusts the file produces nonsense, and a program that crashes is no better. This project reads the lines, checks each field, rejects bad lines with a reason and reports on the rest. It is the same job as in the earlier projects, now in C, where every step needs care.
The library gives you the tools, and each has a trap. strtok_r splits a string at delimiters, but it modifies the string and skips empty fields, so a line such as “5,shed” has two tokens, which the program must count. strtod converts text to a double and, unlike atof, tells you where it stopped through its second argument, so that you can reject text such as “9.9abc”, where the conversion stops before the end. It also sets errno for values out of range. The program checks that at least one character was consumed and that the whole token was used, and then applies the range limits of -50 and 60 degrees.
| Check | How |
|---|---|
| Field count | Count tokens from strtok_r; expect 3 |
| Whole value is a number | strtod with endptr; endptr must reach the end |
| Range | -50 to 60 inclusive |
| Group by sensor | Fixed table of names with sums and counts |
#define _DEFAULT_SOURCE
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct { const char *name; int count; double sum, min, max; } Stat;
static const char *check_line(char *line, char *sensor, size_t sensor_size, double *out) {
char *save = NULL;
char *f[4];
int n = 0;
for (char *tok = strtok_r(line, ",", &save); tok && n < 4; tok = strtok_r(NULL, ",", &save)) f[n++] = tok;
if (n != 3) return "wrong field count";
snprintf(sensor, sensor_size, "%s", f[1]);
char *end;
errno = 0;
double v = strtod(f[2], &end);
if (end == f[2] || *end != '\0' || errno) return "not a number";
if (v < -50 || v > 60) return "out of range";
*out = v;
return NULL;
}
int main(void) {
const char *csv[] = {"id,sensor,value", "1,roof,21.5", "2,roof,22.0", "3,garden,x", "4,garden,18.4", "5,shed", "6,roof,23.1", "7,garden,19.2", "8,shed,9.9abc", "9,shed,10.4", "10,roof,-80.0", "11,garden,20.0"};
size_t rows = sizeof csv / sizeof csv[0];
Stat stats[] = { {"garden", 0, 0, 1e9, -1e9}, {"roof", 0, 0, 1e9, -1e9}, {"shed", 0, 0, 1e9, -1e9} };
int good = 0, rejected = 0;
for (size_t i = 1; i < rows; i++) {
char line[64], sensor[16];
snprintf(line, sizeof line, "%s", csv[i]);
double v;
const char *why = check_line(line, sensor, sizeof sensor, &v);
if (why) { rejected++; printf("line %zu: %s\n", i + 1, why); continue; }
for (size_t s = 0; s < 3; s++) if (strcmp(stats[s].name, sensor) == 0) {
stats[s].count++; stats[s].sum += v;
if (v < stats[s].min) stats[s].min = v;
if (v > stats[s].max) stats[s].max = v;
}
good++;
}
printf("rows: %zu, valid: %d, rejected: %d\n", rows - 1, good, rejected);
for (size_t s = 0; s < 3; s++)
printf("%-7s %d readings, mean %.3f, min %.1f, max %.1f\n", stats[s].name, stats[s].count, stats[s].sum / stats[s].count, stats[s].min, stats[s].max);
return 0;
}
line 4: not a number
line 6: wrong field count
line 9: not a number
line 11: out of range
rows: 11, valid: 7, rejected: 4
garden 3 readings, mean 19.200, min 18.4, max 20.0
roof 3 readings, mean 22.200, min 21.5, max 23.1
shed 1 readings, mean 10.400, min 10.4, max 10.4
The program read 11 data rows, accepted 7 and rejected 4, each with its line number and reason: line 4 not a number; line 6 wrong field count; line 9 not a number; line 11 out of range. The value “x” fails because strtod consumes nothing, the line “5,shed” has only two fields, “9.9abc” fails because the conversion stops before the end of the token, and -80.0 is a valid number but outside the plausible range of -50 to 60. The table shows each sensor’s count, mean, minimum and maximum, computed from the valid rows only: garden 3 readings, mean 19.200, roof 3 readings, mean 22.200, shed 1 readings, mean 10.400.
To verify the report, the course wrote the same rules independently in Python, with its own splitting, a strict regular expression for numbers and the same limits. It rejected the same lines, 4, 6, 9, 11, for the same reasons, and its per-sensor statistics, [(‘garden’, ‘3’, ‘19.200’, ‘18.4’, ‘20.0’), (‘roof’, ‘3’, ‘22.200’, ‘21.5’, ‘23.1’), (‘shed’, ‘1’, ‘10.400’, ‘10.4’, ‘10.4’)], are identical to the table. Parsing is where C programs most often go wrong, and an independent implementation is the best way to find a mistake in either one.
Check by hand: of the 11 rows, 4 are bad (lines 4, 6, 9, 11), leaving 7. The roof has the valid values 21.5, 22.0, 23.1, whose mean is 22.200, and the -80.0 reading was left out.
They give zero for text that is not a number and report no error. Use strtol and strtod with the end pointer, and check errno for overflow.
strtok_r writes terminator bytes into the string it splits. Work on a copy in a buffer, as the program does, if you need the original afterwards, and never split a string literal.
Every program in this lesson was compiled with GCC 13 using -std=c17 -Wall -Wextra and run while the course was written. Compilers and platforms differ, so check your compiler’s documentation, and the C standard drafts, for details that the standard leaves open. strtok_r is POSIX, not standard C, and needs _DEFAULT_SOURCE with -std=c17.
Practice
Make the field count and the limits configurable with constants. Add a rule that rejects a sensor name that is not in the table. Write the rejected lines to a second file and check one statistic by hand.
Check what you learned
Five quick questions. Pick an answer and you will see straight away whether it is right and why.
What does strtod’s second argument tell you?
- Where the conversion stopped
- The sign
- The size of the number
- The locale
The end pointer.
Why was “9.9abc” rejected?
- It is too large
- It has a decimal point
- It starts with 9
- The conversion stopped before the end of the token
endptr was not at the terminator.
Why copy a line before strtok_r?
- It is faster
- It is required by C
- It encrypts it
- strtok_r modifies the string
It writes zero bytes into it.
How was the report verified?
- By running twice
- By trusting it
- By an independent Python implementation
- It was not
Every line and statistic matched.
What should a report do with a bad line?
- Stop
- Ignore it silently
- Reject it with a reason and continue
- Fix it
Bad data is normal.
Summary
- Check field counts and number syntax before using a value.
- strtod with endptr detects trailing junk and no digits.
- Reject bad lines with reasons and carry on.
- An independent implementation verifies the report.
Questions
What does errno do for strtod?
It is set to ERANGE when the value is too large or too small to represent. Set it to zero before the call and check it afterwards.
Is strtok_r portable?
It is POSIX and widely available, but not standard C. The standard has strtok, which is not thread safe. On Windows, strtok_s plays this role.
How do I handle quoted CSV fields?
Splitting on commas breaks on quotes and embedded commas. Use a real CSV parsing library for those files.
