Counting Words, Lines and Characters in a Text File in C

Reading Text File in C

This C program takes a filename as a command-line parameter and reads the specified text file line by line. It counts the number of characters and words in each line and prints the results. Additionally, it displays the total number of lines in the text file.

The file name should include either the complete physical path or just the file name if the file is in the same directory as the program executable. The program has been updated for better readability, correctness, and improved handling of spaces and tabs.

Enhance your knowledge of C programming with these valuable resources:

  1. File Handling Tutorial
  2. C Programming Tutorials
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[]) {
    FILE *fp;
    int nchars, nwords, nlines;
    int lastnblank; /* 0 iff the last character was a space or tab */    char c;

    if (argc != 2) {
        printf("Usage: %s filename\n", argv[0]);
        exit(EXIT_FAILURE);
    }

    if ((fp = fopen(argv[1], "r")) == NULL) {
        perror("fopen");
        exit(EXIT_FAILURE);
    }

    nchars = nwords = nlines = lastnblank = 0;
    while ((c = getc(fp)) != EOF) {
        nchars++;

        if (c == '\n') {
            if (lastnblank)
                nwords++;

            printf("words=%d, characters=%d\n", nwords, nchars);
            nchars = nwords = lastnblank = 0;
            nlines++;
        } else {
            if ((c == ' ' || c == '\t') && lastnblank)
                nwords++;

            lastnblank = (c != ' ' && c != '\t');
        }
    }

    // Handle the case when the last line doesn't end with a newline character
    if (lastnblank)
        nwords++;

    printf("words=%d, characters=%d\n", nwords, nchars);
    printf("lines=%d\n", nlines + (nlines > 0 || nchars > 0 ? 1 : 0));

    fclose(fp);
    return 0;
}
M. Saqib: Saqib is Master-level Senior Software Engineer with over 14 years of experience in designing and developing large-scale software and web applications. He has more than eight years experience of leading software development teams. Saqib provides consultancy to develop software systems and web services for Fortune 500 companies. He has hands-on experience in C/C++ Java, JavaScript, PHP and .NET Technologies. Saqib owns and write contents on mycplus.com since 2004.
Related Post