From 67a02be00818117552240e2c92fa5dddb242f909 Mon Sep 17 00:00:00 2001 From: g1n Date: Thu, 30 Jun 2022 10:51:13 +0300 Subject: [PATCH] Add wc util --- src/wc.c | 115 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 115 insertions(+) create mode 100644 src/wc.c diff --git a/src/wc.c b/src/wc.c new file mode 100644 index 0000000..95cfd8f --- /dev/null +++ b/src/wc.c @@ -0,0 +1,115 @@ +#include +#include +#include +#include +#include + +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; +}