by Dinesh Thakur Category: File Handling

Let us use a while loop in conjunction with the getc macro to read a text file character by character as explained in Program. The counting of characters and lines is very straight forward, the code for which is given below.

/* count characters and lines in text file */

nchar = nline = 0;

while ((ch= getc(fp)) != EOF) {

   nchar++;

   if (ch == '\n')

   nline++;

}

A complete program to count the number of characters, words and lines in a given text file is given below.

#include <stdio.h>

#include <ctype.h>

#include "fileopen.c"

int main()

{

    FILE *fp;

    char fname[50];

    int nchar, nword, nline;

    int ch, in_word;

    /* read file name and open it as a text file for reading */

    fp = fileopen(fname, "rt", "Enter input file name:");

    /* count characters, words and lines in text file */

    nchar = nword = nline = 0;

    in_word = 0;

    while ((ch= getc(fp)) != EOF) {

             nchar++;

         if (ch == '\n')

            nline++;ยท

           if (in_word == 0) {

              if (!isspace(ch)) {

                 in_word = 1;

                 nword++;

              }

          }

        else if (isspace(ch))

                 in_word = 0;

     }

       printf("Characters: %d Words: %d Lines: %d\n'',nchar, nword, nline);

               fclose(fp);

                 return 0;

}

The program output that shows the statistics of a file containing the above program (with file function included) is given below.

Enter input file name: filestat.c

Characters: 1270 Words: 185 Lines: 56



About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.SC (Computer Science), MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.