I'm opening and reading a dictionary file and counting how many words are in the file. Then I'm storing each word individually in an array of strings. After that, I sorted the words by length and in alphabetical order, using the funtion qsort()
. Right now, I'm trying to access the table and count how many words have the same length, but I'm have some difficulties to decide on how I should proceed next. The code I have written so far is this:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_STR 100
/* Sorting the words by length and alphabtichal order,
being legnth priority number one */
int compare(const void *a, const void *b){
const char **str_a = (const char **)a;
const char **str_b = (const char **)b;
int len1 = strlen(*str_a);
int len2 = strlen(*str_b);
if (len1 < len2) return -1;
if (len1 > len2) return 1;
return strcmp(*str_a, *str_b);
}
int main (int argc, char *argv[]){
FILE *fp = NULL;
int i = 0, n_total_palavras = 0;
char str[MAX_STR];
int count = 0;
char **Words;
fp = fopen("words.dict", "r");
if (fp == NULL){
exit (0);
}
while (fscanf(fp,"%s",str) == 1){
n_total_palavras++;
}
Words = (char **)malloc(n_total_palavras * sizeof (char *));
if (Words == NULL){
exit(0);
}
for (i = 0; i < n_total_palavras; i++){
Words[i] = NULL;
}
rewind (fp);
while (fscanf(fp,"%s",str) == 1){
Words[count] = (char*)malloc((strlen(str)+1) * sizeof(char));
strcpy(Words[count], str);
count++;
}
qsort(Words, n_total_palavras, sizeof(Words[0]), compare);
/* for(i = 0; i < n_total_palavras; i++){
printf("%s\n", Words[i]);
}
*/
fclose(fp);
return 0;
}
I'm trying to obtain something like:
4 letters words: 2018
5 letters words: 170
6 letters words: 10
(...)
Any idea on how I should look at this ?