file-handling · beginner · ~10 min
Stream a file byte-by-byte and tally.
long count_byte(const char *path, int ch);
Open path, count how many times the byte ch appears, close. Return the
count, or -1 if the file can't be opened (or path is NULL).
fgetc until EOF.ch.Counting newlines this way is exactly how wc -l works; the same loop counts any byte.
#include <stdio.h>
long count_byte(const char *path, int ch) {
/* TODO */
(void)path; (void)ch;
return -1;
}
Storing fgetc in a char (breaks EOF detection). Forgetting fclose.
Byte not present → 0. Missing file → -1.
O(filesize).
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.