// Implements a dictionary's functionality
include
include
include
include
include
include
include
include "dictionary.h"
const int HASHTABLE_SIZE = 65536;
typedef struct node { char word[LENGTH + 1]; struct node *next; } node;
node* hashtable[HASHTABLE_SIZE];
int hash_table(const char* hashtabl) { unsigned int hash = 0; for (int i=0, n=strlen(hashtabl); i
// Returns true if word is in dictionary else false bool check(const char *word) { // make lower case words char lcword[LENGTH+1]; // convert to lowercase, as we need this to lookup. TODO: change from length to length of word for (int i = 0; i < LENGTH; i++) { lcword[i] = tolower(word[i]); } // set cursor node *cursor = hashtable[hash(lcword)];
while (cursor != NULL)
{
// check node's word, ignoring case
if (strcasecmp(word, cursor->word) == 0)
{
return true;
}
cursor = cursor->next;
}
return false;
}
// Load dictionary into memory, returning true if successful else false bool load(const char *dictionary) { char word[LENGTH+1];
// open my dictionnary file (read)
FILE *dicptr = fopen(dictionary, "r");
while (fscanf(dicptr, "%s", word) != EOF)
{
// make new word.
node *new_node = malloc(sizeof(node));
// check for any error
if (new_node == NULL)
{
unload();
return false;
}
else
{
// copy word in to node
strcpy(new_node->word, word);
int n = hash(new_node->word);
// insert in to my list
new_node->next = hashtable[n];
hashtable[n] = new_node;
}
}
// close dicptr
fclose(dicptr);
return true;
}
// Unloads dictionary from memory, returning true if successful else false bool unload(void) { // TODO for (int i = 0; i < HASHTABLE_SIZE; i++) { node *cursor = hashtable[i];
while (cursor != NULL)
{
node* tmp = cursor;
cursor = cursor->next;
free(tmp);
}
free(cursor);
}
return true;
}
edit
button is under the question, select the code and hit the{}
button in the format bar. It's hard to tell without proper formatting, but thesize
function seems to be missing. It comes betweenload
andunload
in the distro code.