Parse a text file safely in C

8 steps · about 2 h 55 min · Intermediate

  1. Open a file and check the result (reference, cppreference, 20 min)

    Every later operation depends on handling a missing or inaccessible file explicitly.

  2. 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.

  3. Trim line endings without assumptions (reference, cppreference, 15 min)

    strcspn handles either newline convention and a final line with no terminator.

  4. Convert integers with range checks (reference, cppreference, 30 min)

    strtol exposes the end position and overflow that atoi hides.

  5. Grow a record array without losing it (reference, cppreference, 25 min)

    Assigning realloc through a temporary pointer preserves the original allocation on failure.

  6. Sort records with a correct comparator (reference, cppreference, 25 min)

    A comparator must define consistent ordering without overflowing on subtraction.

  7. Distinguish EOF from a read error (reference, cppreference, 15 min)

    A loop ending does not prove the whole file was read successfully.

  8. 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.