2 Copyright © 2013 Alastair Stuart
4 This program is open source software: you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation, either version 3 of the License, or
7 (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
24 #define VERSION "0.01"
33 size_t total_lines
= 0;
34 size_t total_words
= 0;
35 size_t total_chars
= 0;
37 void usage(char* program
)
39 printf("Usage: %s [options] [file ...]\n", program
);
40 printf("Counts words, lines, and characters.\n"
42 " -c, --bytes Print the number of bytes.\n"
43 " -m, --chars Print the number of characters.\n"
44 " -l, --lines Print the number of lines.\n"
45 " -w, --words Print the number of words.\n"
47 " --help Print this message.\n"
48 " --version Show version info.\n"
50 "If no file is given or file is '-', standard input is read.\n");
53 void word_count(FILE* file
)
61 while (c
!= EOF
|| c2
!= EOF
)
68 if ((isprint(c
) && !isblank(c
) && c
!= '\n') &&
69 (isblank(c2
) || c2
== EOF
|| c2
== '\n')) {
76 chars
--; // reading 2 characters at once
77 // causes chars to miscount
84 printf("%zu\t", lines
);
87 printf("%zu\t", words
);
90 printf("%zu\t", chars
);
93 printf("%zu\t", chars
);
97 int main(int argc
, char* argv
[])
101 static struct option long_options
[] = {
102 {"bytes", no_argument
, NULL
, 'c'},
103 {"chars", no_argument
, NULL
, 'm'},
104 {"lines", no_argument
, NULL
, 'l'},
105 {"words", no_argument
, NULL
, 'w'},
106 {"help", no_argument
, NULL
, 1},
107 {"version", no_argument
, NULL
, 2},
112 while ((c
= getopt_long(argc
, argv
, "cmlw",
113 long_options
, NULL
)) != -1)
133 printf("wc (mutos) v"VERSION
"\n");
136 fprintf(stderr
, "Run '%s --help' for usage.\n",
143 if (!flags
.bytes
&& !flags
.chars
&& !flags
.lines
&& !flags
.words
) {
149 if ((argc
- optind
) == 0) {
154 FILE* file_array
[argc
- optind
];
155 memset(file_array
, 0, sizeof(FILE*) * (argc
- optind
));
157 for (int i
= optind
, j
= 0; i
< argc
; i
++, j
++)
162 if (strcmp(argv
[i
], "-") == 0) {
163 file_array
[j
] = stdin
;
164 } else if (s
.st_mode
& S_IFDIR
) { // we can't word count a directory
165 file_array
[j
] = NULL
;
166 fprintf(stderr
, "%s: %s: %s\n",
167 argv
[0], "Is a directory", argv
[i
]);
170 file_array
[j
] = fopen(argv
[i
], "r");
174 size_t num_files
= 0;
175 for (int i
= 0; i
< (argc
- optind
); i
++)
178 word_count(file_array
[i
]);
179 printf("%s\n", argv
[optind
+ i
]);
186 printf("%zu\t", total_lines
);
189 printf("%zu\t", total_words
);
192 printf("%zu\t", total_chars
);
195 printf("%zu\t", total_chars
);