I'm trying to create a program that will read a text file and list each unique word and list how many times they appear.
I believe that I need to first sort the words and then count it but I'm not sure how to do this.
This is what I have so far
Code:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define MAXWORD 100
#define MAXLINE 256
int main() {
FILE *infile;
char *pos;
char buffer[MAXLINE];
char string[MAXLINE];
char *words[MAXWORD];
int counter=0;
int i;
buffer[0] = '\0';
infile = fopen("C:\\Users\\Owner\\Documents\\c\\filetocount.txt", "rt");
if (infile == NULL) {
printf("Cannot open file\n");
} else {
while ((pos=fgets(buffer, MAXLINE, infile)) != NULL) {
while ((sscanf(pos, "%s", string) > 0) && counter < MAXWORD) {
words[counter] = (char *) malloc(strlen(string)+1);
if (words[counter] == NULL) {
;
} else {
strcpy(words[counter], string);
++counter;
}
pos += strlen(string)+1;
}
}
}
for (i=0; i<counter; i++)
printf("%s\n", words[i]);
for (i=0; i<counter; i++)
free(words[i]);
getchar();
return 0;
}