Advertisement
Guest User

Untitled

a guest
Sep 28th, 2016
58
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.17 KB | None | 0 0
  1. #include <stdbool.h>
  2. #include <stdlib.h>
  3. #include <stdio.h>
  4. #include <ctype.h>
  5. #include "dictionary.h"
  6.  
  7. // declaring trie structure
  8. typedef struct trie
  9. {
  10. bool is_word;
  11. struct trie* letters[27];
  12. } trie;
  13.  
  14. trie* head;
  15.  
  16. /**
  17. * Loads dictionary into memory. Returns true if successful else false.
  18. */
  19. bool load(const char* dictionary)
  20. {
  21.  
  22. //declaring first node of the trie and pointing in to NULL
  23. head = (struct trie*)malloc(sizeof(trie));
  24.  
  25. //declare word count for the number of words loaded to the dictionary
  26. int words = 0;
  27.  
  28. //set all root node pointers to null
  29. for (int i = 0; i < 27; i++)
  30. {
  31. head->letters[i] = NULL;
  32. }
  33.  
  34. // open dictionary file ==> need to set the cursor at the beginning of the file each time
  35. FILE* inptr = fopen(dictionary, "r");
  36. if (inptr == NULL)
  37. {
  38. printf("Could not open %s.\n", dictionary);
  39. return 2;
  40. }
  41.  
  42. //declare new trie to jump thru characters
  43. trie* current = head;
  44.  
  45. //go thru each character in the file until end of file
  46. for (int i = 0, ch = 1; ch != EOF; i++)
  47. {
  48. //read the current character from file
  49. ch = fgetc(inptr);
  50.  
  51. // if the character is a letter or an apostrophe
  52. if (ch != '\n')
  53. {
  54. //if the pointer for the character doesn't exist (equals NULL) allocate memory
  55. if (current->letters[tolower(ch) - 'a'] == NULL)
  56. {
  57. current->letters[tolower(ch) - 'a'] = (struct trie*)malloc(sizeof(trie));
  58. }
  59.  
  60. //move forward in our trie structure
  61. current = current->letters[tolower(ch) - 'a'];
  62. }
  63.  
  64. //if the character read indicates the end of the line
  65. else
  66. {
  67. //indicate that this is a word in our dictionary in the trie
  68. current->is_word = true;
  69. //reset our current node to the beginning of the trie
  70. current = head;
  71. //count number of words loaded in the dictionary
  72. words++;
  73. }
  74. }
  75.  
  76. printf ("%i words loaded to the dictionary\n", words);
  77.  
  78. // close infile
  79. fclose(inptr);
  80.  
  81. return true;
  82. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement