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
- Take the filename from
argv[1]and open it withfopen(..., "r"), failing loudly tostderrif it doesn’t exist. - Read one character at a time with
fgetc()until it returnsEOF. - Classify each character with
isalpha()/isdigit()/isspace()and bump the right counters. - Words need one bit of state:
in_word. A word starts at the first non-space character after whitespace — counting transitions, not characters. - 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 1 — sample.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) plusEOF(−1). Store it in acharand either EOF becomes indistinguishable from byte 255, or the loop never ends on platforms wherecharis unsigned. This is the #1 file-handling interview trap.in_wordflag — 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 Unixwcdefines 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.longcounters — a text file bigger than 2 GB would overflowinton most platforms;longis 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 -cbehaves.
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 anint— the EOF sentinel problem - State-flag word counting (transition counting, not character counting)
- Command-line arguments with
argc/argvand cleanstderrerror reporting - The
<ctype.h>classification family in real use
Related C Programs
- Find the Size of a File in C — the
fseek/ftellroute to one of these numbers - Find Memory Leaks with Valgrind — verify this program’s file handle hygiene yourself
- Sort the Characters of a String in C
- K&R Exercise Solutions — Exercises 1-8 through 1-11 are this program in pieces
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.