Count Characters, Words, and Lines in a File in C

Counting the characters in a file is the “hello world” of C file handling — but done properly it teaches four things at once: the fgetc() read loop, why ch must be an int and not a char, the <ctype.h> classification functions, and word counting with a state flag. This version is a miniature wc: it reports characters, letters, digits, whitespace, words, and lines for any file passed on the command line — tested, warning-free C89 with proper error handling.

How It Works — Step by Step

  1. Take the filename from argv[1] and open it with fopen(..., "r"), failing loudly to stderr if it doesn’t exist.
  2. Read one character at a time with fgetc() until it returns EOF.
  3. Classify each character with isalpha() / isdigit() / isspace() and bump the right counters.
  4. Words need one bit of state: in_word. A word starts at the first non-space character after whitespace — counting transitions, not characters.
  5. Lines = newline characters seen.

C Program to Count Characters, Words, and Lines in a File

#include <stdio.h>
#include <ctype.h>

int main(int argc, char *argv[])
{
    FILE *fp;
    int ch, in_word = 0;
    long characters = 0, letters = 0, digits = 0, spaces = 0;
    long lines = 0, words = 0;

    if (argc != 2) {
        fprintf(stderr, "Usage: %s <filename>\n", argv[0]);
        return 1;
    }
    fp = fopen(argv[1], "r");
    if (fp == NULL) {
        fprintf(stderr, "Cannot open '%s'\n", argv[1]);
        return 1;
    }

    while ((ch = fgetc(fp)) != EOF) {     /* ch must be int, not char: EOF! */
        characters++;
        if (isalpha(ch)) {
            letters++;
        } else if (isdigit(ch)) {
            digits++;
        }
        if (isspace(ch)) {
            spaces++;
            in_word = 0;
        } else if (!in_word) {
            in_word = 1;
            words++;                      /* first non-space after a gap */
        }
        if (ch == '\n') {
            lines++;
        }
    }
    fclose(fp);

    printf("Characters: %ld\n", characters);
    printf("Letters:    %ld\n", letters);
    printf("Digits:     %ld\n", digits);
    printf("Whitespace: %ld\n", spaces);
    printf("Words:      %ld\n", words);
    printf("Lines:      %ld\n", lines);
    return 0;
}

How to Compile and Run

gcc -ansi -Wall -Wextra -o countchars countchars.c
./countchars sample.txt

Sample Input and Output

Test 1sample.txt containing:

Hello World 123
Second line here

Output:

Characters: 33
Letters:    24
Digits:     3
Whitespace: 6
Words:      6
Lines:      2

Hand-check: 15 visible characters + newline on line one (16), 16 + newline on line two (17) = 33. Six words, two newlines. ✓

Test 2 — a missing file fails cleanly:

./countchars nope.txt
Cannot open 'nope.txt'

Code Explanation

  • int ch — the most important line. fgetc() returns every possible byte value (0–255) plus EOF (−1). Store it in a char and either EOF becomes indistinguishable from byte 255, or the loop never ends on platforms where char is unsigned. This is the #1 file-handling interview trap.
  • in_word flag — words are counted at the whitespace→non-whitespace transition, so runs of multiple spaces, tabs, and newlines don’t inflate the count. This is exactly how Unix wc defines a word (and this program is K&R Exercise 1-11’s grown-up sibling).
  • fprintf(stderr, ...) — errors go to stderr so they don’t pollute output when you pipe the results.
  • long counters — a text file bigger than 2 GB would overflow int on most platforms; long is the cheap insurance.
  • Note that “characters” here means bytes — in a UTF-8 file, one multi-byte character counts as several bytes, which is also how wc -c behaves.

Time and Space Complexity

Aspect Complexity Why
Time O(n) every byte examined exactly once
Space O(1) six counters and a flag — file size is irrelevant

What This Program Teaches

  • Why fgetc() demands an int — the EOF sentinel problem
  • State-flag word counting (transition counting, not character counting)
  • Command-line arguments with argc/argv and clean stderr error reporting
  • The <ctype.h> classification family in real use

Related C Programs

Test yourself: our free C Programming Quiz app for Android has 150+ questions with explanations for every answer — including a dedicated File I/O category.

Recommended Book

Chapter 7 of The C Programming Language by Kernighan & Ritchie covers file I/O the way it was designed to be learned. Also on Amazon.com.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>