I'm trying to Write a C program to read the file out3.dat.txt and print the ten most highly ranked keywords and their counts.
For example:
Sample out3.dat.txt file
word, 2
wordtwo, 1
wordthree, 2
wordfour, 3
Expected Output
wordfour, 3
word, 2
wordthree, 2
wordtwo, 1
My approach is to sort the counts for the keywords in decreasing order and then locate the respective keywords corresponding to the highest counts. I just want to assume that the ranking is only by the count occurrence (i.e. keywords with the same counts have the same rank regardless of their alphabetical ordering).
This is what I have attempted and struggled with:
#include <stdio.h>
#include <string.h>
int main(void) {
FILE *inp;
FILE *outp;
int n, i, j;
char item, item2, keywords[42][20], word[20];
inp = fopen("out3.dat.txt", "r");
outp = fopen("out4.dat.txt", "w");
while (!feof(inp)) {
for (i = 0; i < 42; ++i) {
fgets(keywords[i], 20, inp);
int l = strlen(keywords[i]) - 1;
if (keywords[i][l] == '\n')
keywords[i][l] = '\0';
}
}
//V--------below is the issue but I cant seem to figure it out-----V
for (i = 0; i < 42; ++i) {
strcpy(word, keywords[i]);
for (j = 1; j < 20; ++j) {
if (word[j] == ' ') {
++j;
//printf("%c\n", words[i][j]);
item = word[j];
//printf("%c\n", item);
--j;
}
++i;
if (keywords[i][j] == ' ') {
++j;
item2 = keywords[i][j];
--j;
}
--i;
if (item >= item2 && n < 10) {
printf("%s\n", word);
n++;
}
//printf("%d\n", r);
}
}
fclose(inp);
fclose(outp);
return (0);
}