Files in C: solved exercise
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.
Problem statement
Open a text file in read mode and count:
- number of lines,
- total number of characters.
C solution
#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;
}Expected output
Lines: 3
Chars: 74Exact values depend on the contents of data.txt.
Recommended edge case
Test a file without a trailing newline.
Example content:
one
two
threeIf the file does not end with \n, line counting can be off by one unless your logic handles it.
Common mistakes
- Not checking whether
fopenreturnedNULL. - Forgetting to call
fclose. - Treating
EOFas a real file character. - Assuming every line ends with
\nand miscounting the final line.
Time and space complexity
- Time: O(n), scanning each character once.
- Extra space: O(1).
Practical use
This pattern is used in log processing, tracing pipelines, and event-file analysis in modern observability workflows.
Recommended next exercise
- Strings in C: solved exercises with strlen, strcpy, and strcmp
- fread and fwrite in C: solved binary file exercise
- Binary search in C: solved exercise on sorted arrays
- All C exercises
Guided practice and next step
If you want a complete path with progressive difficulty:
FAQ
Is this good to learn file I/O in C?
Yes. It is a direct base before writing files (fprintf) and binary I/O (fread/fwrite).
Where can I continue with guided practice?
At Programming in C in 100 Solved Exercises and C Exercises. Kindle Unlimited: View on Amazon.
How should I practice this exercise type to improve faster?
Start with small inputs, run edge cases (empty, one item, max capacity), then rewrite the solution from scratch without copying.