Count Lines, Words, and Characters in File in C, C++, Java & Python – Code with Explanation & Examples in Short and Simple

   

C Program

#include <stdio.h>
#include <ctype.h>
void countFileStats() {
    FILE *f = fopen("data.txt", "r");
    int c, lines = 0, words = 0, chars = 0, inWord = 0;
    while ((c = fgetc(f)) != EOF) {
        chars++;
        if (c == '\n') lines++;
        if (isspace(c)) inWord = 0;
        else if (!inWord) { words++; inWord = 1; }
    }
    fclose(f);
    printf("Lines:%d Words:%d Chars:%d", lines, words, chars);
}

C Output

Input:  
Hello world
This is Python  

Output:  
Lines: 2 Words: 5 Chars: 24

C++ Program

#include <fstream>
#include <iostream>
using namespace std;
void countFileStats() {
    ifstream f("data.txt");
    string w, line;
    int lines = 0, words = 0, chars = 0;
    while (getline(f, line)) {
        lines++;
        chars += line.size() + 1;
        istringstream iss(line);
        while (iss >> w) words++;
    }
    cout << "Lines:" << lines << " Words:" << words << " Chars:" << chars;
}

C++ Output

Input:  
Hello world
This is Python 

Output:  
Lines: 2 Words: 5 Chars: 24


JAVA Program

import java.io.*;
void countFileStats() throws Exception {
    BufferedReader br = new BufferedReader(new FileReader("data.txt"));
    int lines = 0, words = 0, chars = 0;
    String line;
    while ((line = br.readLine()) != null) {
        lines++;
        chars += line.length() + 1;
        words += line.split("\\s+").length;
    }
    br.close();
    System.out.println("Lines:" + lines + " Words:" + words + " Chars:" + chars);
}

JAVA Output

Input:  
Hello world
This is Python  

Output:
Lines: 2 Words: 5 Chars: 24


Python Program

def count_file_stats():
    with open("data.txt", "r") as f:
        txt = f.read()
        lines = txt.count('\n') + 1
        words = len(txt.split())
        chars = len(txt)
        print("Lines:", lines, "Words:", words, "Chars:", chars)

Python Output

Input:  
Hello world
This is Python 

Output:  
Lines: 2 Words: 5 Chars: 24


In-Depth Explanation
Example
If your data.txt has:


Hello world
This is Python

There are:

2 lines (after each line)

5 words (Hello, world, This, is, Python)

24 characters (including newlines and spaces)

The program reads the file and maintains line, word, and character counters — increasing them as needed.

Real-Life Analogy
Imagine examining a document similarly to the way MS Word displays to you stats: word number, character number, and lines. These values give you insight into the size of your content, help you estimate reading time, or check content limits in resumes, essays, or SMS drafts.

That's what you're doing programmatically here — being the backend for a word counter application.

Why It Matters
Line counting, word counting, and character counting is important in:

Text analytics

Compiler design (token and line parsing)

File comparison or validation

Performance metrics in logs and data files

It also instructs:

How to process files line-by-line

How to use string manipulation for real-world text operations

Managing state transitions (such as tracking word boundaries)

What You Learn from This
You learn to:

Open and read files

Count using conditions and logic

Track text structure efficiently (such as word boundaries)

Use built-in functions and methods (split, readline, fgetc, etc.)

This is a solid foundation for more complex tasks such as:

Tokenizers

Line parsers

File statistics generators

Interview Relevance and Real Projects
This problem is commonly asked in:

College practical exams

Programming interviews (file handling round)

Test automation scripts (log parsers)

Real-world applications include:

Making word counters or spell checkers

Pre-processing data for machine learning or NLP

Comparing file sizes and formats

Monitoring logs in DevOps and system monitoring

SEO-Optimized Explanation
Line, word, and character counting in a file is a common utility utilized in text analysis, word processing, and file systems. It introduces the basics of file I/O, string manipulation, and text-based measures to beginners. This reasoning can be applied while developing log analyzers, document editors, and machine learning/NLP data preprocessing scripts. Practicing counting lines, words, and characters will improve your file handling skills and set you up well for programming in the real world when knowing text structure is crucial.