wc/wc.c
2023-09-08 23:38:51 +02:00

45 lines
858 B
C

#include <stdio.h>
#include <unistd.h> // read, isatty
// STDIN_FILENO
int process_fn(int fn)
{
char c[1];
int seen_word=0;
int seen_sep=0;
int num_words = 0;
while (read(fn, c, sizeof(c)) > 0) {
if(*c == '\n' || *c == ' ' || *c == '\t'){
seen_sep = 1;
} else {
seen_word = 1;
}
if(seen_word && seen_sep){
num_words++;
seen_sep = seen_word = 0;
}
}
if(seen_word){
num_words++;
}
printf("%i\n",num_words);
return 0;
}
int main(int argc, char** argv)
{
if (!isatty(STDIN_FILENO)) {
return process_fn(STDIN_FILENO);
} else if (argc > 1) {
FILE* fp = fopen(argv[1], "r");
if (!fp) {
perror("Could not open file");
return 1;
}
return process_fn(fileno(fp));
} else {
printf("To do");
}
return 0;
}