In this tutorial, you'll learn how to count the number of characters, words, and lines in a text file using the C programming language. This is essentially a from-scratch implementation of the Unix wc command, and it's one of the most common file-handling exercises in exams and interviews. The program reads the file one character at a time with fgetc(), uses a simple state machine to detect word boundaries, and counts newline characters for the line total.
📝 Problem Statement
Write a program in C to count the number of characters, words, and lines in a text file.
⚙️ How the Program Works
The program reads one byte at a time and updates three counters:
- Characters: increment for every byte read (except
EOF). - Lines: increment every time the current character is
'\n'. - Words: increment when the previous character was whitespace (or the file just started) and the current character is not whitespace. That is the moment a new word begins.
The key variable is in_word — a boolean that tracks whether the reader is currently inside a word or in the whitespace between words.
💻 Complete C Program
#include <stdio.h>
#include <ctype.h>
int main(void)
{
FILE *fp;
char filename[100];
int ch;
long chars = 0, words = 0, lines = 0;
int in_word = 0; /* 0 = between words, 1 = inside a word */
printf("Enter the filename: ");
scanf("%99s", filename);
fp = fopen(filename, "r");
if (fp == NULL)
{
printf("Error: Could not open file '%s'.\n", filename);
return 1;
}
while ((ch = fgetc(fp)) != EOF)
{
chars++;
if (ch == '\n')
lines++;
if (isspace((unsigned char)ch))
{
in_word = 0;
}
else if (!in_word)
{
in_word = 1;
words++;
}
}
fclose(fp);
printf("\nStatistics for '%s':\n", filename);
printf(" Characters : %ld\n", chars);
printf(" Words : %ld\n", words);
printf(" Lines : %ld\n", lines);
return 0;
}🖥️ Sample Output
Assume sample.txt contains the following three lines:
sample.txt:
The quick brown fox jumps over the lazy dog.The dog barked. The fox ran.
The dog and the fox are friends.
Running the program:
Statistics for 'sample.txt':
Characters : 118
Words : 21
Lines : 3
The exact character count includes spaces, punctuation, and the three newline characters. Your count may differ by a few bytes depending on the trailing newline at the end of the file.
🔍 Line-by-Line Explanation
| Line / Code | Explanation |
|---|---|
#include <ctype.h> |
Provides isspace(), which returns non-zero for spaces, tabs, newlines, carriage returns, form feeds, and vertical tabs. |
int ch; |
fgetc returns int, not char. Using int allows it to return EOF (-1) distinctly from byte value 255. |
long chars, words, lines |
long is used so that large files (more than ~2 billion bytes) are counted correctly on most platforms. |
int in_word = 0; |
A simple state flag. 0 means "we are outside a word", 1 means "we are inside a word". |
while ((ch = fgetc(fp)) != EOF) |
Reads one byte at a time until the end of the file. |
chars++; |
Each byte (including spaces and newlines) counts as a character. |
if (ch == '\n') lines++; |
Each newline marks the end of one line. |
isspace((unsigned char)ch) |
The cast to unsigned char avoids undefined behavior when ch is 128–255. |
if (!in_word) { in_word = 1; words++; } |
We just transitioned from whitespace to a non-whitespace character — that's the start of a new word. |
fclose(fp); |
Releases the file handle. Always call this. |
wc -l) count newlines only, so a file ending without a newline reports one fewer line than you might expect. Adjust the logic if you want to count the last partial line.
🧠 How the Word Count Works
The word counter relies on a simple state machine with two states:
- Outside a word (
in_word = 0): skip whitespace until a non-whitespace character appears. When that happens, we've found the beginning of a new word — incrementwordsand switch toin_word = 1. - Inside a word (
in_word = 1): keep reading until whitespace appears. Then switch back toin_word = 0so the next non-whitespace character can start a new word.
This approach correctly handles multiple spaces, tabs, mixed whitespace, and leading/trailing whitespace — no special cases needed.
🐛 Common Pitfalls
- Declaring
chaschar: On platforms wherecharis signed, a byte value of 0xFF appears as -1 and terminates the loop early. Always useintwithfgetc. - Forgetting the
unsigned charcast: Passing a signedchartoisspaceis undefined behavior for values above 127. - Counting the trailing newline: Files that end with
\ncount that newline as the end of the last line — which is correct. Files that don't end with\nreport one fewer line. Decide which convention you want. - Missing punctuation: This program treats punctuation as part of the word.
"dog."and"dog"are both one word. If you want to treat punctuation as separators, useisalnum()instead of just!isspace(). - Skipping
fclose: File descriptors are a limited resource. Always close what you open.
🔁 Common Variations
- Count vowels: Replace
isspacewithstrchr("aeiouAEIOU", ch)and increment a vowel counter. - Count alphanumeric words: Use
isalnum((unsigned char)ch)to define word characters, so"dog."counts as one word but"dog."and"dog"are treated identically. - Count only lines: Drop the
charsandwordscounters — this becomes a minimalwc -lclone. - Count only non-blank characters: Only increment
charswhen!isspace(ch).
💡 Tips & Best Practices
- Use
long(orunsigned long long) for counters to handle large files. - Cast
chtounsigned charbefore passing it toisspace,isalpha, or any otherctype.hfunction. - Compile with
gcc -Wall -Wextra -std=c11 -gto catch type warnings. - Open in binary mode (
"rb") if you want an exact byte count, since text mode may translate line endings on Windows.