Count Characters, Words & Lines — C File Handling Solution
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

C Program to Count the Number of Characters, Words, and Lines in a Text File

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.

C program to count characters, words, and lines in a text file using fgetc and isspace, with step-by-step explanation.

📝 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:

  1. Characters: increment for every byte read (except EOF).
  2. Lines: increment every time the current character is '\n'.
  3. 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:

Contents of 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:

Console: Enter the filename: sample.txt

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.
⚠️ Important: The line count does not include a final "phantom" line if the file ends with content but no trailing newline. Some tools (like Unix 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 — increment words and switch to in_word = 1.
  • Inside a word (in_word = 1): keep reading until whitespace appears. Then switch back to in_word = 0 so 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 ch as char: On platforms where char is signed, a byte value of 0xFF appears as -1 and terminates the loop early. Always use int with fgetc.
  • Forgetting the unsigned char cast: Passing a signed char to isspace is undefined behavior for values above 127.
  • Counting the trailing newline: Files that end with \n count that newline as the end of the last line — which is correct. Files that don't end with \n report 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, use isalnum() instead of just !isspace().
  • Skipping fclose: File descriptors are a limited resource. Always close what you open.

🔁 Common Variations

  • Count vowels: Replace isspace with strchr("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 chars and words counters — this becomes a minimal wc -l clone.
  • Count only non-blank characters: Only increment chars when !isspace(ch).

💡 Tips & Best Practices

  • Use long (or unsigned long long) for counters to handle large files.
  • Cast ch to unsigned char before passing it to isspace, isalpha, or any other ctype.h function.
  • Compile with gcc -Wall -Wextra -std=c11 -g to catch type warnings.
  • Open in binary mode ("rb") if you want an exact byte count, since text mode may translate line endings on Windows.

📖 Related Tutorials in This Series

  • File Handling Assignments — Complete Index
  • 4. Read and Display the Contents of a Text File
  • 2. Search for a Specific Word in a Text File
  • Count Vowels in a File
  • Count Words and Lines in a File
  • 15. Copy the Contents of One Text File into Another
  • Files FAQ

Previous Problem: -->> 4. Read and Display the Contents of a Text File   ||   Next Problem: -->> 6. Delete a Specific Line from a Text File

Back to Index: -->> File Handling Assignments in C


C Language

  • Home
  • Why C Language
  • History of C Language
  • Applications of C Language
  • Introduction To C
    • What is Program?
    • Structure of C Program
    • Working Of C Program
    • CHARACTER SET
    • VARIABLES AND IDENTIFIERS
    • BUILT-IN DATA TYPES
    • OPERATORS AND EXPRESSIONS
    • CONSTANTS AND LITERALS
    • SIMPLE ASSIGNMENT STATEMENT
    • BASIC INPUT/OUTPUT STATEMENT
    • SIMPLE 'C' PROGRAMS
    • Assignments
  • Operators in C Programming
    • Arithmetic Operators
    • Assignment Operators
    • Increment and Decrement Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Other Operators
    • Assignments
  • CONDITIONAL STATEMENTS
    • DECISION MAKING WITHIN A PROGRAM
    • CONDITIONS
    • IF STATEMENT
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • SWITCH CASE
    • Assignments
  • LOOPS STATEMENTS
    • Introduction to Loops
    • GO TO Statement
    • Do while Loop
    • While Loop
    • Nested While Loop
    • Difference Between While and Do while
    • Difference Between Goto and loop
    • while loop assignments
    • C FOR Loop
    • C For loop examples
    • Nested for loop
    • Nested for loop examples
    • Infinite while Loops
    • Infinite for Loops
    • Continue in Loops
    • break in Loops
    • difference while do..while & for
    • Assignments
  • Arrays
    • One Dimensional Array
    • Declaring 1D Arrays
    • Initilization of 1D arrays
    • Accessing element of one 1D Array
    • Read and Display 1D Arrays
    • Two Dimensional Arrays
    • Declare 2D Arrays
    • Read and Display 2D Arrays
    • Assignments/Examples
  • Functions
    • Introduction
    • Need For User-Defined Function
    • Multiple Function Program
    • Modular Programming
    • Elements Of User Defined Function
    • Function Definition
    • Function Declaration
    • Types of functions
    • Nesting of Function
    • Recursion
    • Passing Array To Functions
    • Scope,Visibility and Lifetime of Variables
    • Assignments
  • Structure
    • Introduction
    • Array vs Structure
    • Defining Structure
    • Declaring Structure Variables
    • Type Defined Structure
    • Accessing Structure Members
    • Structure Initilization
    • Copying & Comparing Structure Variables
    • Array of Structure
    • Arrays Within Structure
    • Structures Within Structures
    • Structures and Functions
    • Structure Examples/Assignments
  • Union
    • Define Union
    • Create and use Union
    • Difference Between Structure and Union
    • Union Examples
    • Union FAQ
  • Pointers
    • What Are Pointers In C?
    • How Do We Use Pointers In C?
    • Declaration Of A Pointer
    • The Initialization Of A Pointer
    • Syntax Of Pointer Initialization
    • Use Of Pointers In C
    • The Pointer To An Array
    • The Pointer To A Function
    • The Pointer To A Structure
    • Types Of Pointers
    • The Null Pointer
    • The Void Pointer
    • The Wild Pointer
    • The Near Pointer
    • The Huge Pointer
    • The far Pointer
    • dangling pointer
    • Accessing Pointers- Indirectly And Directly
    • Pros Of Using Pointers In C
    • Cons Of Pointers In C
    • Applications Of Pointers In C
    • The & Address Of Operator In C
    • How To Read The Complex Pointers In C?
    • Practice Problems On Pointers
  • File Processiong
    • File Handling In C
    • Types Of Files In C
    • Operations Done In File Handling
    • File Examples
    • Binary Files
    • count words,lines in a file
    • Copy files
    • Update File
    • count vowels in a file
  • Preprocessor
    • Macro substitution division
    • File Inclusion
    • Conditional Compilation
    • Other directives
    • Examples
  • Dynamic Memory Allocation
    • malloc
    • calloc
    • free
    • realloc
    • Examples
  • Storage Classes
  • Graphics
  • Frequently Asked Interview Questions (FAQ)
    • Introduction To C FAQ
    • Operators FAQ
    • Conditional Statements FAQ
    • Loops FAQ
    • Arrays FAQ
    • Function FAQ
    • Structure FAQ
    • Pointers FAQ
    • Files FAQ
    • Storage classes FAQ
    • Dynamic Memory FAQ
  • Programs/Assignments
    • Introduction To C
    • Operators
    • Conditional Statements
    • Loops
    • Arrays
    • Function
    • Structure
    • Pointers
    • Files
    • Storage classes
    • Dynamic Memory
  • Case Studies
  • Multiple Choice Questions
    • Introduction To C MCQ
    • Operators MCQ
    • Conditional Statements MCQ
    • Loops MCQ
    • Arrays MCQ
    • Function MCQ
    • Structure MCQ
    • Pointers MCQ
    • Files MCQ
    • Storage classes MCQ
    • Dynamic Memory MCQ
    • More MCQ

Get in touch

  • tech2dsm@gmail.com

© Sankalan Data Tech. All rights reserved.