School-Coding-Cpp/sfusi/countOccurrence_textfile.c

50 lines
964 B
C

#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define SIZE_LINE 1000+1
int countOccurrence(FILE * file, const char * word);
int main(void) {
FILE * file = fopen("parole.txt", "rt");
if (file != NULL) {
int countOcc = 0;
countOcc = countOccurrence(file, "l");
printf("Total occurrences: %d\n", countOcc);
fclose(file);
} else {
perror("Error (source)");
}
return 0;
}
int countOccurrence(FILE * file, const char * word) {
char str[SIZE_LINE];
char lowerWord[SIZE_LINE];
int countOcc = 0;
strncpy(lowerWord, word, SIZE_LINE - 1);
lowerWord[SIZE_LINE - 1] = '\0';
for (int i = 0; lowerWord[i] != '\0'; i++) {
lowerWord[i] = tolower(lowerWord[i]);
}
while (fgets(str, sizeof(str), file) != NULL) {
for (int i = 0; str[i] != '\0'; i++) {
str[i] = tolower(str[i]);
}
if (strstr(str, lowerWord) != NULL) {
countOcc++;
}
}
return countOcc;
}