mp-utils/src/wc.c

127 lines
2.1 KiB
C

/* wc.c -- program to count and display the number of lines, words and one of bytes or characters in the named files */
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <ctype.h>
#include "support.h"
enum
{
C,
M,
L,
W,
OUTWORD,
INWORD,
/* character or byte */
COB = 0,
WORDS = 1,
LINES = 2,
};
int main(int argc, char **argv)
{
char state;
int c, i;
char par[4] = {1};
/* M and C conflict; M counts actual characters (theoretically), so we should go with that as the default */
par[C] = 0;
int count[3] = {0};
int total[3] = {0};
FILE *fd;
state = OUTWORD;
c = i = 0;
fd = 0;
/* process our parameters */
for(; (c = getopt(argc, argv, "cmlw")) != -1; c = 0)
{
switch(c)
{
case 'c': par[C] = 1;
par[M] = 0;
break;
case 'm': par[M] = 1;
par[C] = 0;
break;
case 'l': par[L] = 1;
break;
case 'w': par[W] = 1;
break;
/* Fall-through to default from ':' */
case ':':
case '?':
default: throw(NEEDARG_FAIL, mastrcat(argv[0], "[-c|-m] [-lw] [file ...]"));
break;
}
}
/* for every file we're given... */
for(fd = 0, i = optind; i < argc; fclose(fd), i++)
{
/* ...open our file... */
if( !(fd = fopen(argv[i], "r")))
{
printf("%d %d\n", i, optind);
exit(1);
}
/* ...then read until EOF... */
for(c = 0; (c = fgetc(fd)) != EOF;)
{
/* ...and count the goods as we go. */
if(!(isblank(c) || c == '\n'))
{
if(state == OUTWORD)
{
count[WORDS]++;
}
state = INWORD;
}
else
{
if(c == '\n')
{
count[LINES]++;
}
state = OUTWORD;
}
count[COB]++;
}
/* ...then print our total and reset. */
printf("%d %d %d %s\n", count[LINES], count[WORDS], count[COB], argv[i]);
total[COB] += count[COB];
total[WORDS] += count[WORDS];
total[LINES] += count[LINES];
count[COB] = 0;
count[WORDS] = 0;
count[LINES] = 0;
}
if((argc-optind) > 1)
{
printf("%d %d %d total\n", total[LINES], total[WORDS], total[COB]);
}
exit(0);
}