/** * dictionary.c * * Computer Science 50 * Problem Set 5 * * Implements a dictionary's functionality. */ #include #include #include #include #include "dictionary.h" node* root; unsigned int words_loaded = 0; /** * Returns true if word is in dictionary else false. */ bool check(const char* word) { // ptr to traverse trie starting from root node* ptr = root; int i = 0; int letter; // loops through input word while (true) { letter = (int) *(word + i); if (isupper(word[i])) { if (ptr->children[letter - 'A'] == NULL) { return false; } else if (word[i + 1] == '\0') { if (ptr->is_word == true) { return true; } ptr = ptr->children[letter - 'A']; } } else if (islower(word[i])) { if (ptr->children[letter - 'a'] == NULL) { return false; } else if (word[i + 1] == '\0') { if (ptr->is_word == true) { return true; } ptr = ptr->children[letter - 'A']; } } else if (word[i] == '\'') { if (ptr->children[26] == NULL) { return false; } else if (word[i + 1] == '\0') { if (ptr->is_word == true) { return true; } ptr = ptr->children[letter - 'A']; } } i++; } } /** * Loads dictionary into memory. Returns true if successful else false. */ bool load(const char* dictionary) { FILE* dict = fopen(dictionary, "r"); if (dict == NULL) { printf("Dictionary could not be opened.\n"); return false; } root = calloc(1, sizeof(node)); node* ptr = root; for (char c = fgetc(dict); c != EOF; c = fgetc(dict)) { if (ptr->children[c - 'a'] == NULL) { ptr->children[c - 'a'] = calloc(1, sizeof(node)); ptr = ptr->children[c - 'a']; } else { ptr = ptr->children[c - 'a']; } //check for end of word if (c == '\0') { ptr->is_word = true; ptr = root; words_loaded++; } } return true; } /** * Returns number of words in dictionary if loaded else 0 if not yet loaded. */ unsigned int size(void) { return words_loaded; } void unloader(node* track) { node* ptr = track; int i = 0; while (i != 26) { if (ptr->children[i] != NULL) { unloader(ptr->children[i]); } i++; } node* temp = ptr; free(temp); } /** * Unloads dictionary from memory. Returns true if successful else false. */ bool unload(void) { unloader(root); return true; }