wc/ww.c
NunoSempere 496cd811a1 small readability reorder
Thought a bit about whether having OR instead of AND
changes performance, and concluded it probably didn't.

In particular, think about when it jumps to the inner
part of the if/else condition
2023-09-09 16:21:03 +02:00

42 lines
895 B
C

#include <stdio.h>
#include <unistd.h>
int wc(FILE* fp)
{
char c[1];
int word = 0, num_words = 0;
int fn = fileno(fp);
while (read(fn, c, sizeof(c)) > 0) {
if (*c != ' ' && *c != '\n' && *c != '\t') {
word = 1;
} else {
if (word) {
num_words++;
word = 0;
}
}
}
num_words+=word;
printf("%i\n", num_words);
return 0;
}
int main(int argc, char** argv)
{
if (argc == 1) {
return wc(stdin);
} else if (argc > 1) {
FILE* fp = fopen(argv[1], "r");
if (!fp) {
perror("Could not open file");
return 1;
}
return wc(fp) && fclose(fp);
} else {
printf("Usage: ww file.txt\n");
printf(" or: cat file.txt | ww\n");
printf(" or: ww # read from user-inputted stdin\n");
}
return 0;
}