Write a program that reads text from a file and keeps a count of the number of characters, lines, and words in the file. In addition, print each word in the input on a separate line.
This program is similar to the counting programs we have done before in count3.c. You can use the input file count3.dat. To count words we need to add steps to detect words by finding the beginning and end of a word.
initialize counts to zreo
at the beginning, we are not in a word
get the first character
while there are more characters
increment the character count
if the character is a newline
increment the line count
if we are not in a word, and the character is not a delimiter
(we have just found the beginning of the word)
increment the word count
remember we are now in a word
otherwise, if we are already in a word and the character is a delimeter
(we have just gone beyond the end of the word)
remember we are not in a word
print a newline
if we are in a word
print the current character
get the next character
print count results
The code is in wds.c. In this program we use macros and functions in chrutil.h and chrutil.c.
wds.c file
/* Program File: wds.c
Other Source Files: chrutil.c
Header Files: tfdef.h, chrutil.h
This program reads standard input characters and prints each word on a
separate line. It also counts the number of lines, words, and characters.
All characters are counted including the newline and other control
characters, if any.
*/
#include <stdio.h>
#include "tfdef.h"
#include "chrutil.h"
#define INTERACT
/*
*/
main()
{ signed char ch;
int inword, /* flag indicating when in a word */
lns, wds, chrs; /* Counters for lines, words, chars. */
#ifdef INTERACT
printf("***Line, Word, Character Count Program***\n\n");
printf("Type characters, EOF to quit\n");
#endif
lns = wds = chrs = 0; /* initialize counters to 0 */
inword = FALSE; /* before beginning we are not in a word */
while ((ch = getchar()) != EOF) /* while there are more characters */
{ chrs = chrs + 1; /* count characters */
if (ch == '\n') /* if newline char */
lns = lns + 1; /* count lines */
/* if not in a word and not a delimiter */
/* then this must be the beginning of a word */
if (!inword && !delimitp(ch)) /* if not in word and not delim. */
{ inword = TRUE; /* remember we are in a word */
wds = wds + 1; /* count words */
}
/* otherwise if in a word, but found a delimiter */
/* then we just went beyond the end of the word */
else if (inword && delimitp(ch)) /* if in word and a delimiter*/
{ inword = FALSE; /* we are no longer in a word*/
putchar('\n'); /* end word with a newline */
}
if (inword) /* if in a word */
putchar(ch); /* print the character */
}
/* print the results */
printf("Lines = %d, Words = %d, Characters = %d\n",
lns, wds, chrs);
}