2023-09-08 20:42:06 +00:00
|
|
|
#include <stdio.h>
|
2023-09-09 09:01:04 +00:00
|
|
|
#include <unistd.h>
|
2023-09-08 20:42:06 +00:00
|
|
|
|
2023-09-09 09:22:41 +00:00
|
|
|
int wc(FILE* fp)
|
2023-09-08 21:02:54 +00:00
|
|
|
{
|
2023-09-15 08:20:42 +00:00
|
|
|
register int c;
|
2023-09-09 14:21:03 +00:00
|
|
|
int word = 0, num_words = 0;
|
2023-09-15 08:20:42 +00:00
|
|
|
while ((c = getc(fp)) != EOF) {
|
|
|
|
if (c != ' ' && c != '\n' && c != '\t') {
|
2023-09-09 14:21:03 +00:00
|
|
|
word = 1;
|
2023-09-15 09:19:40 +00:00
|
|
|
} else if (word) {
|
|
|
|
num_words++;
|
|
|
|
word = 0;
|
2023-09-08 22:07:22 +00:00
|
|
|
}
|
|
|
|
}
|
2023-09-15 09:19:40 +00:00
|
|
|
num_words += 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-15 09:19:40 +00:00
|
|
|
int wc_status = wc(fp);
|
|
|
|
int fclose_status = fclose(fp);
|
|
|
|
return (wc_status == 0) && (fclose_status == 0);
|
|
|
|
// can't do return wc_status == 0 && fclose_status == 0;
|
|
|
|
// because then if wc returns with -1, fclose is not called.
|
2023-09-08 21:23:18 +00:00
|
|
|
} else {
|
2023-09-10 13:05:28 +00:00
|
|
|
printf("Usage: wc file.txt\n");
|
|
|
|
printf(" or: cat file.txt | wc\n");
|
|
|
|
printf(" or: wc # read from user-inputted stdin\n");
|
2023-09-08 21:23:18 +00:00
|
|
|
}
|
2023-09-08 21:02:54 +00:00
|
|
|
return 0;
|
2023-09-08 20:42:06 +00:00
|
|
|
}
|