-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathwc.c
More file actions
95 lines (86 loc) · 1.64 KB
/
wc.c
File metadata and controls
95 lines (86 loc) · 1.64 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
/* See LICENSE file for copyright and license details. */
#include <ctype.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "util.h"
static void output(const char *, long, long, long);
static void wc(FILE *, const char *);
static bool lflag = false;
static bool wflag = false;
static char cmode = 0;
static long tc = 0, tl = 0, tw = 0;
int
main(int argc, char *argv[])
{
bool many;
char c;
FILE *fp;
while((c = getopt(argc, argv, "clmw")) != -1)
switch(c) {
case 'c':
case 'm':
cmode = c;
break;
case 'l':
lflag = true;
break;
case 'w':
wflag = true;
break;
default:
exit(EXIT_FAILURE);
}
many = (argc > optind+1);
if(optind == argc)
wc(stdin, NULL);
else for(; optind < argc; optind++) {
if(strcmp(argv[optind], "-") == 0) argv[optind] = "/dev/stdin";
if(!(fp = fopen(argv[optind], "r")))
eprintf("fopen %s:", argv[optind]);
wc(fp, argv[optind]);
fclose(fp);
}
if(many)
output("total", tc, tl, tw);
return EXIT_SUCCESS;
}
void
output(const char *str, long nc, long nl, long nw)
{
bool noflags = !cmode && !lflag && !wflag;
if(lflag || noflags)
printf(" %5ld", nl);
if(wflag || noflags)
printf(" %5ld", nw);
if(cmode || noflags)
printf(" %5ld", nc);
if(str)
printf(" %s", str);
putchar('\n');
}
void
wc(FILE *fp, const char *str)
{
bool word = false;
char c;
long nc = 0, nl = 0, nw = 0;
while((c = getc(fp)) != EOF) {
if(cmode != 'm' || UTF8_POINT(c))
nc++;
if(c == '\n')
nl++;
if(!isspace(c))
word = true;
else if(word) {
word = false;
nw++;
}
}
tc += nc;
tl += nl;
tw += nw;
output(str, nc, nl, nw);
}