file-handling · beginner · ~10 min

Count a byte's occurrences in a file

Stream a file byte-by-byte and tally.

Challenge

Your job

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

Hints

  1. Loop with fgetc until EOF.
  2. Compare each byte to ch.

Why this matters

Counting newlines this way is exactly how wc -l works; the same loop counts any byte.

Starter code

#include <stdio.h>
long count_byte(const char *path, int ch) {
    /* TODO */
    (void)path; (void)ch;
    return -1;
}

Common mistakes

Storing fgetc in a char (breaks EOF detection). Forgetting fclose.

Edge cases to handle

Byte not present → 0. Missing file → -1.

Complexity

O(filesize).

Background lessons

Up next

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.