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