home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
Club Amiga de Montreal - CAM
/
CAM_CD_1.iso
/
files
/
264a.lha
/
UnixUtil
/
wc.c
< prev
next >
Wrap
C/C++ Source or Header
|
1989-07-09
|
3KB
|
148 lines
/* wc.c - count the number of lines, words, and characters in a file. *
* *
* wc [<file> ...] *
* *
* wc (C) 1988 by Gary L. Brant *
* *
* :ts=8 */
#include <stdio.h>
#define FALSE 0
#define TRUE 1
#define COUNT_LINES 4
#define COUNT_WORDS 2
#define COUNT_CHARS 1
int cur_flag, def_flag = COUNT_LINES | COUNT_WORDS | COUNT_CHARS;
int head;
long lines, words, chars;
long tlines=0, twords=0, tchars=0;
char string[] = " ";
main (argc, argv) /* count lines, words, chars in input */
int argc;
char *argv[];
{
register int i = 0, j;
register char ch;
FILE *input, *fopen ();
void fclose ();
cur_flag = def_flag;
while (++i < argc) {
if (argv [i][0] == '-') { /* remember to bump i in loop */
def_flag = cur_flag;
cur_flag = 0;
for (j = 1; (ch = argv[i][j]) != '\0'; j++)
switch (ch) {
case 'l':
cur_flag |= COUNT_LINES;
break;
case 'w':
cur_flag |= COUNT_WORDS;
break;
case 'c':
cur_flag |= COUNT_CHARS;
break;
default:
cur_flag = def_flag;
}
} else {
++head;
if ((input = fopen (argv[i], "r")) == NULL) {
fputs ("wc: can't open ", stderr);
fputs (argv[i], stderr);
putc ('\n', stderr);
continue;
} else {
wc (input, argv[i]);
fclose (input);
}
}
}
if (!head)
wc (stdin, "");
else if ( head > 1)
print (tlines, twords, tchars, "total");
}
/* count words, etc. in 1 file
* inspired by example from: K.&R. P. 18 */
wc (fp, fn)
FILE *fp;
char *fn;
{
register int in, c;
in = FALSE;
lines = words = chars = 0;
while ((c = getc (fp)) != EOF) {
++chars;
if (c == '\n') {
++lines;
in = FALSE;
} else if (c == ' ' || c == '\t')
in = FALSE;
else if (!in) {
in = TRUE;
++words;
}
}
print (lines, words, chars, fn);
tlines += lines;
twords += words;
tchars += chars;
}
/* print - print counts for a file */
print (lines, words, chars, fn)
long lines, words, chars;
char *fn;
{
if (cur_flag & COUNT_LINES) {
convert (lines, string);
fputs (string, stdout);
}
if (cur_flag & COUNT_WORDS) {
convert (words, string);
fputs (string, stdout);
}
if (cur_flag & COUNT_CHARS) {
convert (chars, string);
fputs (string, stdout);
}
if (head)
fputs (fn, stdout);
putc ('\n', stdout);
}
convert (val, string)
register long val;
register char *string;
{
register int i = 7;
if (val == 0)
string[i--] = '0';
while (val != 0) {
register long j, k;
j = val / 10;
k = val - 10 * j;
val = j;
string[i--] = '0' + k;
if (i < 0)
break;
}
while (i >= 0)
string[i--] = ' ';
}
_wb_parse ()
{
}