The C Page

See all articles from Sinc-Link v9 n1
Author(s): Timothy Swenson
Publication: Sinc-Link
Pub Details: Sinc-Link v9 n1 (Volume 9, Issue 1)
Date: January/February 1991
Pages: 24

This month’s program is a simple version of the UNIX utility wc (word count). This program reads in a text file and counts all of the lines, words, and characters.

The structure of this program is similar to last month’s program. The section that gets the file is the same. The while statement is the same. It’s the block in the while statement that has changed. One line is different. C has a way of assigning the same value to a number of variables. The line nl=nw=nc=0; sets all of the variables to zero. This way you do not have to write three individual lines to set each variable to zero.

Items in single quotes are not taken as literals, but translated to ASCII. ‘\n’ stands for newline and ‘\t’ stands for tab. The C manual shows about 6 more of these.

Note that the define statements are commented out. In the stdio_h file, YES and NO are already defined. In other implementations they may not be.

Define statements are used to create one version of a constant. With a constant defined with a define statement, anytime the compiler comes across the constant it is replaced with the actual number.

In the printf statement the %d stands for a decimal. C knows to put a decimal value at this point. The first decimal variable it finds in the statement goes in the first %d. The C manual defines others besides %d.

I’ll let the reader muddle through how the program works.

/* Program 6 */
#include <stdio_h>

/* #define YES 1
#define NO 0
The two constants are defined in stdio_h for this
implementation, but may not be for others
*/

main () {
int c, fd, nl, nw, nc, word;
char file[20];

printf("Enter File: ");
gets(file);
fd = fopen(file,"r");
if (fd == NULL) {
printf("File Open Error");
abort(1);
}
word = NO;
nl = nw = nc = 0;

while (( c = getc(fd)) != EOF) {
++nc;
if ( c == '\n')
++nl;
if ( c == ' ' || c == '\n' || c == '\t')
word = NO;
else if (word == NO) {
word = YES;
++nw;
}
}
fclose(fd);
printf("Lines: %d Words: %d Chars: %d",nl,nw,nc);
}

Note: Type-in program listings on this website use ZMAKEBAS notation for graphics characters.