wc/ww.c

48 lines
1.2 KiB
C
Raw Normal View History

#include <stdio.h>
#include <unistd.h>
2023-09-09 09:22:41 +00:00
int wc(FILE* fp)
2023-09-08 21:02:54 +00:00
{
2023-09-08 21:22:57 +00:00
char c[1];
2023-09-09 09:22:41 +00:00
int seen_word = 0, seen_sep_after_word = 0, num_words = 0;
int fn = fileno(fp);
2023-09-08 21:22:57 +00:00
while (read(fn, c, sizeof(c)) > 0) {
2023-09-09 09:22:41 +00:00
if (*c == '\n' || *c == ' ' || *c == '\t') {
if (seen_word) {
seen_sep_after_word = 1;
}
2023-09-08 22:07:22 +00:00
} else {
2023-09-09 09:22:41 +00:00
seen_word = 1;
2023-09-08 22:07:22 +00:00
}
2023-09-09 09:22:41 +00:00
// exercise: what happens if you only track seen_sep,
// instead of seen_sep_after_word?
// test with: $ echo " hello world" | ./wc
2023-09-08 22:07:22 +00:00
if (seen_word && seen_sep_after_word) {
num_words++;
seen_sep_after_word = seen_word = 0;
}
}
2023-09-09 09:22:41 +00:00
num_words+=seen_word;
2023-09-08 22:07:22 +00:00
printf("%i\n", num_words);
2023-09-08 21:23:18 +00:00
return 0;
2023-09-08 21:02:54 +00:00
}
int main(int argc, char** argv)
{
2023-09-09 09:22:41 +00:00
if (argc == 1) {
return wc(stdin);
2023-09-08 21:23:18 +00:00
} else if (argc > 1) {
FILE* fp = fopen(argv[1], "r");
if (!fp) {
perror("Could not open file");
return 1;
}
2023-09-09 09:22:41 +00:00
return wc(fp) && fclose(fp);
2023-09-08 21:23:18 +00:00
} else {
2023-09-08 22:06:56 +00:00
printf("Usage: ww file.txt\n");
2023-09-08 22:07:22 +00:00
printf(" or: cat file.txt | ww\n");
2023-09-09 09:22:41 +00:00
printf(" or: ww # read from user-inputted stdin\n");
2023-09-08 21:23:18 +00:00
}
2023-09-08 21:02:54 +00:00
return 0;
}