Software & Finance

C Programming (Turbo C++ Compiler) - Counting Characters, Words and lines from a file or string buffer

Here I have given the source code to count the number of Characters, Words and lines from a file or string buffer.


GetWordCount function is written in C language and tested with turbo c++ compiler.


Source Code

 // WordCount.c : Defines the entry point for the console application.


#include <stdio.h>


bool GetWordCount(const char *srcFileName, int &numChars, int &numWords, int &numLines)


    const int len = 4096;

    int nc, wc, lc;

    int nBytesRead ;


    FILE *istream = fopen(srcFileName, "rb");


    if (istream == 0)

        return false;


    numChars = 0;

    numWords = 0;

    numLines = 0;





        if( feof(istream))


        nBytesRead = fread(buf, 1, len, istream);

        if(nBytesRead <= 0)


        GetWordCount(buf, nBytesRead, nc, wc, lc);

        numChars += nc;

        numWords += wc;

        numLines += lc;


    } while(1);



    return true;




int main()


    int nc, wc, lc;

    GetWordCount("c:\\kathir.txt", nc, wc, lc);


    printf("Chars: %d\n", nc);

    printf("Words: %d\n", wc);

    printf("Lines: %d\n", lc);


    return 0;




The file kathir.txt contains the following lines:

Welcome to website.
Thank you very much for using our web site.


The output is given below:


Chars: 87

Words: 13

Lines: 2

Press any key to continue . . .