-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwc.c
More file actions
39 lines (31 loc) · 835 Bytes
/
wc.c
File metadata and controls
39 lines (31 loc) · 835 Bytes
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
#include <stdio.h>
#include <ctype.h>
int main(int argc, char *argv[]) {
if (argc < 2) {
fprintf(stderr, "Usage: wc filename\n");
return 1;
}
for (int i = 1; i < argc; i++) {
FILE *f = fopen(argv[i], "r");
if (!f) {
perror(argv[i]);
continue;
}
int lines = 0, words = 0, chars = 0;
int c, prev_space = 1;
while ((c = fgetc(f)) != EOF) {
chars++;
if (c == '\n')
lines++;
if (isspace(c))
prev_space = 1;
else {
if (prev_space) words++;
prev_space = 0;
}
}
printf("%s %d %d %d\n", argv[i], lines, words, chars);
fclose(f);
}
return 0;
}