Write a function that a receives file name of a txt
file, which contains unknown number of words of max length 10
each. Print the word with the most occurrences. Assume the input is correct and contains at least one word.
Code
#define MAX_CHARS 11
int mostFrequentWord(char* filename) {
char ch;
int i, j, k, occurrence, counter = 1, maximum = 0;
char *index_max = NULL;
char **arr;
FILE *file = fopen(filename, "r");
while((ch = fgetc(file)) != EOF) {
if(ch == ' ') {
counter++;
}
}
rewind(file);
arr = (char**) calloc(counter, sizeof(char*));
for (k = 0; k < counter; k++) {
arr[k] = (char*) calloc(MAX_CHARS, sizeof(char));
}
while ((ch = fgetc(file)) != EOF) {
if (ch == ' '){
i++;
j = 0;
} else {
arr[i][j] = ch;
j++;
}
}
for (i= 0; i < counter; i++) {
occurrence = 0;
for (j = i; j < counter; j++) {
if (!strcmp(*(arr + i), *(arr + j))){
occurrence++;
}
}
if (occurrence > maximum) {
maximum = occurrence;
index_max = *(arr+i);
}
}
if (index_max != NULL){
printf("The most frequent word is \"%s\" with %d occurrences.\n", index_max, maximum);
}
for ( i = 0; i < counter; i++ ) {
free(arr[i]);
}
free(arr);
return 0;
}
Example
Input (test.txt
):
test one two test three test
Output:
The most frequent word is "test" with 3 occurrences.
One thing I think I'm missing (and not sure what's the way to do it) is to check the success of calling functions that use system resources.
Any review is appreciated.