School-Coding-Cpp/sfusi/countWord_textfile.c

40 lines
689 B
C

#include <stdio.h>
#include <string.h>
#define SIZE_LINE 1000+1
int countWord(const char * str);
int main(void) {
FILE * file = fopen("parole.txt", "rt");
if (file != NULL) {
char str[SIZE_LINE];
int countWrd = 0;
while (fgets(str, sizeof(str), file)) {
countWrd = countWrd + countWord(str);
}
printf("Total words: %d\n", countWrd);
fclose(file);
} else {
perror("Error (source)");
}
return 0;
}
int countWord(const char * str) {
char buffer[SIZE_LINE];
int countWrd = 0;
strcpy(buffer, str);
for (char * pc = buffer; (pc = strtok(pc, " \n")) != NULL; pc = NULL) {
countWrd++;
}
return countWrd;
}