
Donald W. answered 04/15/22
Senior Software Engineer with over 25 years of industry experience
Here's my implementation:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, char **argv) {
if (argc < 2) {
printf("Usage: %s <file>\n", argv[0]);
return 0;
}
FILE *f = fopen(argv[1], "r");
int words_to_read = 0;
if (fscanf(f, "%d", &words_to_read) > 0) {
int wordcount = 0;
char *words[20] = {0};
int wordscount[20] = {0};
for (int i=0; i<words_to_read && i <20; i++) {
char buffer[80];
if (fscanf(f, "%s", buffer) > 0) {
int j;
for (j=0; j<wordcount; j++) {
if (!strcmp(buffer, words[j])) {
wordscount[j]++;
break;
}
}
if (j == wordcount) {
words[j] = strdup(buffer);
wordscount[j]++;
wordcount++;
}
}
}
for (int i=0; i<wordcount; i++) {
printf("%s - %d\n", words[i], wordscount[i]);
free(words[i]);
}
}
fclose(f);
return 0;
}
And here's the output given a file with the above input:
> ./a.out test.txt
hey - 1
hi - 2
Mark - 1
mark - 1
I decided not to print "hi" twice, since that didn't seem to make sense to do.