file-handling · beginner · ~10 min

Count a byte's occurrences in a file

Stream a file byte-by-byte and tally.

Challenge

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.

Task

Implement long count_byte(const char *path, int ch) that opens path, counts how many bytes equal ch, then closes the file.

Input

  • path: filename of a file the grader writes in the working directory.
  • ch: the byte value to count (as an int, e.g. '\n').

Output

Return the number of matching bytes. Return -1 if the file can't be opened or path is NULL.

Example

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

Edge cases

  • Byte not present: 0.
  • Missing file or NULL path: -1.

Rules

  • Read with fgetc (store the result in an int so EOF is detected); open in binary mode; close before returning.

Why this matters

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

Input format

path: file to scan. ch: byte value to count.

Output format

long count of bytes equal to ch, or -1 on open failure / NULL path.

Constraints

Stream with fgetc into an int; do not store the byte in a char.

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.