This loads a dictionary text file into memory to be used as part of a spell checker. It's part of a larger program, but I wanted general comments so I can clean it up further.
#define TABLESIZE 500
#define LENGTH 45
bool load(const char* dictionary)
{
//initiate hash table
node* hashtable[TABLESIZE];
//open dictionary and check
FILE* dict = fopen(dictionary, "r");
if (dict == NULL)
{
printf("Could not open file.");
return false;
}
//initiate variable to store current word
char* dword = calloc(LENGTH+ 1,sizeof(char));
//read the file
while(fscanf(dict, "%s", dword) != EOF)
{
//if there is a word, create node and put word in it
node* new_node = malloc(sizeof(node));
strcpy(new_node->word,dword);
//find spot in hash table and put it in that bucket
unsigned int hashkey= 0;
for (int counter = 0; dword[counter]!= '\0'; counter++)
{
hashkey = (hashkey*dword[counter] + dword[counter] + counter)%TABLESIZE;
}
//check if spot in table exists; if not, start the linked list
if (hashtable[hashkey] == NULL)
{
hashtable[hashkey] = new_node;
new_node->next = NULL;
}
//otherwise made current node the first, shift rest over
else
{
new_node->next = hashtable[hashkey];
hashtable[hashkey] = new_node;
}
//count words for later use
nwords++;
}
fclose(dict);
return true;
}