Advertisement
rushk

Untitled

Oct 2nd, 2018
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.67 KB | None | 0 0
  1. #include <cs50.h>
  2. #include <stdio.h>
  3. #include <string.h>
  4.  
  5. // Loads dictionary into memory, returning true if successful else false
  6. bool load(const char *dictionary)
  7. {
  8. // open the dictionary
  9. FILE *dict = fopen(dictionary, "r");
  10. if (dict == NULL)
  11. {
  12. fprintf(stderr, "Could not open\n");
  13. return 2;
  14. }
  15.  
  16. // define node
  17. typedef struct node
  18. {
  19. // node has a boolean which if true means you got to the end of the word, if false you still have more letters to go
  20. bool is_word;
  21. // point to next node which is the child
  22. struct node *children[27];
  23. }
  24. node;
  25. node *root;
  26.  
  27. root = malloc(sizeof(node));
  28. root->is_word = false;
  29.  
  30. node *temp;
  31. temp = malloc(sizeof(node));
  32.  
  33. temp = root;
  34.  
  35.  
  36. char s[45];
  37. node *new_node;
  38. for(int i=0; fgets(s, 45, dict) != NULL; i++)
  39. {
  40. for(int j=0, n = strlen(s); j < n - 1; j++)
  41. {
  42. int ascii = s[j] - 97;
  43. printf("%d ", ascii);
  44. if (temp->children[ascii] == NULL)
  45. {
  46. new_node = malloc(sizeof(node));
  47. }
  48. else if (temp->children[ascii] != NULL)
  49. {
  50. temp = new_node;
  51. }
  52. else
  53. {
  54. temp->is_word = true;
  55. }
  56. }
  57. printf("\n");
  58. }
  59.  
  60. printf("This is the dictionary: %s\n", dictionary);
  61. free(root);
  62. fclose(dict);
  63.  
  64. return false;
  65. }
  66.  
  67. int main(int argc, char *argv[])
  68. {
  69. if (argc != 2)
  70. {
  71. printf("error");
  72. return 1;
  73. }
  74. char *dictionary = argv[1];
  75. load(dictionary);
  76. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement