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 ;
    char
buf[4096];

   

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

 

    if (istream == 0)

        return false;

 

    numChars = 0;

    numWords = 0;

    numLines = 0;

 

 

    do

    {

        if( feof(istream))

            break;

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

        if(nBytesRead <= 0)

            break;

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

        numChars += nc;

        numWords += wc;

        numLines += lc;

 

    } while(1);

 

    fclose(istream);

    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;

}

Output


 

The file kathir.txt contains the following lines:

Welcome to softwareandfinance.com 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 . . .