coreutils/src/wc.c

116 lines
2.4 KiB
C

#include <ctype.h>
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
int usage(char *argv0) {
printf("Usage: %s [-c|-m] [-lw] [file ...]\n", argv0);
return 2;
}
bool only_chars = false;
bool only_words = false;
bool only_newlines = false;
void print_counting(int newlines, int chars, int words, char *filename) { // FIXME: this code is not clean
if (only_newlines) {
printf("%d ", newlines);
}
if (only_words) {
printf("%d ", words);
}
if (only_chars) {
printf("%d ", chars);
}
if (!only_chars && !only_words && !only_newlines) {
printf("%d %d %d ", newlines, words, chars);
}
printf("%s\n", filename);
}
int main(int argc, char *argv[]){
char ch;
int opt;
FILE *file = stdin;
int files = 0;
int chars = 0;
int chars_total = 0;
int words = 0;
int words_total = 0;
int newlines = 0;
int newlines_total = 0;
bool finding_word = false;
while ((opt = getopt(argc, argv, ":cmlw")) != -1) {
switch (opt) {
case 'c':
case 'm': // FIXME
only_chars = true;
break;
case 'l':
only_newlines = true;
break;
case 'w':
only_words = true;
break;
case '?':
fprintf(stderr, "%s: invalid option -- '%c'\n", argv[0], optopt);
return usage(argv[0]);
}
}
if (optind == argc) { // FIXME: this code is not clean
goto READ_STDIN;
}
for (; optind < argc; optind++) {
chars = 0;
words = 0;
newlines = 0;
if (strcmp(argv[optind], "-")) {
file = fopen(argv[optind], "r");
if (file == NULL) {
fprintf(stderr, "%s: ", argv[0]);
perror(argv[optind]);
return -1;
}
} else {
file = stdin;
}
READ_STDIN:
files++;
while ((ch = fgetc(file)) != EOF) {
chars++;
if (isspace(ch) && !finding_word) { // FIXME
finding_word = true;
words++;
}
if (ch == '\n') {
newlines++;
}
if (!isspace(ch)) {
finding_word = false; // FIXME
}
}
print_counting(newlines, chars, words, (argv[optind] ? argv[optind] : ""));
chars_total += chars;
words_total += words;
newlines_total += newlines;
if (file != NULL && file != stdin) {
fclose(file);
}
}
if (files > 1) {
print_counting(newlines_total, chars_total, words_total, "total");
}
return 0;
}