-
-
Save hltbra/0000172d98d0652a75f0abdc5c84474f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
int is_blank(int c) { | |
return c == ' ' || c == '\t' || c == '\n'; | |
} | |
int is_opt(char *o, char opt) { | |
return o[0] == '-' && o[1] == opt && o[2] == '\0'; | |
} | |
int main(int argc, char *argv[]) { | |
int total_chars = 0; | |
int total_lines = 0; | |
int total_words = 0; | |
// start with blank to avoid corner case of leading blanks | |
char prev_char = ' '; | |
char c; | |
int count_chars = 0; | |
int count_lines = 0; | |
int count_words = 0; | |
int in_word = 0; | |
int has_options = 0; | |
FILE *fp = stdin; | |
char *filename; | |
for (int i = 1 ; i < argc ; i++) { | |
if (!has_options && argv[i][0] != '-') { | |
fp = fopen(argv[i], "r"); | |
filename = argv[i]; | |
break; | |
} | |
if (is_opt(argv[i], 'c')) { | |
has_options = 1; | |
count_chars = 1; | |
} else if (is_opt(argv[i], 'l')) { | |
has_options = 1; | |
count_lines = 1; | |
} else if (is_opt(argv[i], 'w')) { | |
has_options = 1; | |
count_words = 1; | |
} else { | |
printf("invalid argument \"%s\"\n", argv[i]); | |
return 1; | |
} | |
} | |
if (!has_options) { | |
count_chars = count_lines = count_words = 1; | |
} | |
while ((c = fgetc(fp)) != EOF) { | |
total_chars++; | |
if (c == '\n') { | |
total_lines++; | |
} | |
if (is_blank(c) && !is_blank(prev_char)) { | |
total_words++; | |
} | |
prev_char = c; | |
} | |
// count last word (or first and only word) | |
if (total_chars > 0 && !is_blank(prev_char)) { | |
total_words++; | |
} | |
if (count_lines) { | |
printf("\t%d", total_lines); | |
} | |
if (count_words) { | |
printf("\t%d", total_words); | |
} | |
if (count_chars) { | |
printf("\t%d", total_chars); | |
} | |
if (fp != stdin) { | |
printf(" %s", filename); | |
} | |
printf("\n"); | |
if (fp && fp != stdin) { | |
fclose(fp); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment