-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwc.c
104 lines (95 loc) · 2.79 KB
/
wc.c
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
96
97
98
99
100
101
102
103
104
// Copyright (C) 2021 Benjamin Stürz
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
#define PROG_NAME "wc"
#include <unistd.h>
#include <string.h>
#include <stdio.h>
#include <ctype.h>
#include "errprintf.h"
struct count_result {
size_t words;
size_t lines;
size_t bytes;
};
static struct count_result count(FILE* file) {
struct count_result r = { 0 };
char ch, last_ch = '\0';
while ((ch = fgetc(file)) != EOF) {
if (isspace(ch) && !isspace(last_ch))
++r.words;
if (ch == '\n') ++r.lines;
++r.bytes;
last_ch = ch;
}
return r;
}
#define print(x) { if (i == 0) { i = 1; printf("%zu", (x)); } else printf(" %zu", (x)); }
#define print_result(r) \
if (opt_l) print(r.lines); \
if (opt_w) print(r.words); \
if (opt_c || opt_m) print(r.bytes);
int main(int argc, char* argv[]) {
int opt_c = 0, opt_m = 0, opt_l = 0, opt_w = 0;
int option;
while ((option = getopt(argc, argv, ":cmlw")) != -1) {
switch (option) {
case 'c': opt_c = 1; break;
case 'm': opt_m = 1; break;
case 'l': opt_l = 1; break;
case 'w': opt_w = 1; break;
default: goto print_usage;
}
}
if ((opt_c + opt_m + opt_l + opt_w) == 0)
opt_l = opt_w = opt_m = 1;
int i = 0;
if (optind == argc) {
struct count_result r = count(stdin);
print_result(r);
putchar('\n');
return 0;
}
const int print_total = (argc - optind) > 1;
int ec = 0;
struct count_result total = { 0 };
for (; optind < argc; ++optind) {
i = 0;
const char* path = argv[optind];
FILE* file;
if (strcmp(path, "-") == 0) file = stdin;
else file = fopen(path, "r");
if (!file) {
errprintf("failed to open '%s'", path);
ec = 1;
continue;
}
const struct count_result r = count(file);
print_result(r);
printf(" %s\n", path);
if (file != stdin) fclose(file);
total.lines += r.lines;
total.words += r.words;
total.bytes += r.bytes;
}
if (print_total) {
i = 0;
print_result(total);
puts(" total");
}
return ec;
print_usage:
puts("Usage: wc [-c|-m] [-lw] [file...]");
return 1;
}