Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdbool.h>
- #include <stdlib.h>
- #include <stdio.h>
- #include <ctype.h>
- #include "dictionary.h"
- // declaring trie structure
- typedef struct trie
- {
- bool is_word;
- struct trie* letters[27];
- } trie;
- trie* head;
- /**
- * Loads dictionary into memory. Returns true if successful else false.
- */
- bool load(const char* dictionary)
- {
- //declaring first node of the trie and pointing in to NULL
- head = (struct trie*)malloc(sizeof(trie));
- //declare word count for the number of words loaded to the dictionary
- int words = 0;
- //set all root node pointers to null
- for (int i = 0; i < 27; i++)
- {
- head->letters[i] = NULL;
- }
- // open dictionary file ==> need to set the cursor at the beginning of the file each time
- FILE* inptr = fopen(dictionary, "r");
- if (inptr == NULL)
- {
- printf("Could not open %s.\n", dictionary);
- return 2;
- }
- //declare new trie to jump thru characters
- trie* current = head;
- //go thru each character in the file until end of file
- for (int i = 0, ch = 1; ch != EOF; i++)
- {
- //read the current character from file
- ch = fgetc(inptr);
- // if the character is a letter or an apostrophe
- if (ch != '\n')
- {
- //if the pointer for the character doesn't exist (equals NULL) allocate memory
- if (current->letters[tolower(ch) - 'a'] == NULL)
- {
- current->letters[tolower(ch) - 'a'] = (struct trie*)malloc(sizeof(trie));
- }
- //move forward in our trie structure
- current = current->letters[tolower(ch) - 'a'];
- }
- //if the character read indicates the end of the line
- else
- {
- //indicate that this is a word in our dictionary in the trie
- current->is_word = true;
- //reset our current node to the beginning of the trie
- current = head;
- //count number of words loaded in the dictionary
- words++;
- }
- }
- printf ("%i words loaded to the dictionary\n", words);
- // close infile
- fclose(inptr);
- return true;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement