Files in C: solved exercise to count lines and characters

  2 minutes

If you are searching for files in C solved exercises, this example covers a very common real-world task: open a text file, scan characters, and compute basic metrics.

Open a text file in read mode and count:

  • number of lines,
  • total number of characters.
#include <stdio.h>

int main(void) {
    FILE *f = fopen("data.txt", "r");
    if (f == NULL) {
        perror("Could not open data.txt");
        return 1;
    }

    int c;
    int lines = 0;
    int chars = 0;

    while ((c = fgetc(f)) != EOF) {
        chars++;
        if (c == '\n') {
            lines++;
        }
    }

    fclose(f);

    printf("Lines: %d\n", lines);
    printf("Chars: %d\n", chars);

    return 0;
}
Lines: 3
Chars: 74

Exact values depend on the contents of data.txt.

Test a file without a trailing newline.
Example content:

one
two
three

If the file does not end with \n, line counting can be off by one unless your logic handles it.

  • Not checking whether fopen returned NULL.
  • Forgetting to call fclose.
  • Treating EOF as a real file character.
  • Assuming every line ends with \n and miscounting the final line.
  • Time: O(n), scanning each character once.
  • Extra space: O(1).

This pattern is used in log processing, tracing pipelines, and event-file analysis in modern observability workflows.

If you want a complete path with progressive difficulty:

Yes. It is a direct base before writing files (fprintf) and binary I/O (fread/fwrite).

At Programming in C in 100 Solved Exercises and C Exercises. Kindle Unlimited: View on Amazon.

Start with small inputs, run edge cases (empty, one item, max capacity), then rewrite the solution from scratch without copying.