file-handling · beginner · ~10 min
Stream a file byte-by-byte and tally.
Count how many times a particular byte appears in a file by streaming it one byte at a time — exactly how wc -l counts newlines.
Implement long count_byte(const char *path, int ch) that opens path, counts how many bytes equal ch, then closes the file.
path: filename of a file the grader writes in the working directory.ch: the byte value to count (as an int, e.g. '\n').Return the number of matching bytes. Return -1 if the file can't be opened or path is NULL.
file "cb.txt" = "a\nbb\nccc\n"
count_byte("cb.txt", '\n') -> 3
count_byte("cb.txt", 'c') -> 3
count_byte("cb.txt", 'z') -> 0
count_byte("missing.txt", 'a') -> -1
fgetc (store the result in an int so EOF is detected); open in binary mode; close before returning.Counting newlines this way is exactly how wc -l works; the same loop counts any byte.
path: file to scan. ch: byte value to count.
long count of bytes equal to ch, or -1 on open failure / NULL path.
Stream with fgetc into an int; do not store the byte in a char.
#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.