Parse a text file safely in C
8 steps · about 2 h 55 min · Intermediate
- Open a file and check the result (reference, cppreference, 20 min)
Every later operation depends on handling a missing or inaccessible file explicitly.
- Read complete lines with getline (reference, Linux man-pages project, 25 min)
A length-aware interface grows its buffer and reports exactly how much input it read.
- Trim line endings without assumptions (reference, cppreference, 15 min)
strcspn handles either newline convention and a final line with no terminator.
- Convert integers with range checks (reference, cppreference, 30 min)
strtol exposes the end position and overflow that atoi hides.
- Grow a record array without losing it (reference, cppreference, 25 min)
Assigning realloc through a temporary pointer preserves the original allocation on failure.
- Sort records with a correct comparator (reference, cppreference, 25 min)
A comparator must define consistent ordering without overflowing on subtraction.
- Distinguish EOF from a read error (reference, cppreference, 15 min)
A loop ending does not prove the whole file was read successfully.
- Close the input stream on every exit path (reference, cppreference, 20 min)
One cleanup section makes file ownership visible and prevents descriptors from leaking after partial work.