I did not bother to name this...

From Forensic Dolphin, 1 Month ago, written in C, viewed 25 times.
URL http://codebin.org/view/4f008c0b Embed
Download Paste or View Raw
  1. // Implements a dictionary's functionality
  2.  
  3. #include <ctype.h>
  4. #include <stdbool.h>
  5. #include <stdio.h>
  6. #include <stdlib.h>
  7. include <string.h>
  8.  
  9. #include "dictionary.h"
  10.  
  11. // Represents number of buckets in a hash table
  12. #define N 26
  13.  
  14. // Represents a node in a hash table
  15. typedef struct node
  16. {
  17.     char word[LENGTH + 1];
  18.     struct node *next;
  19. }
  20. node;
  21.  
  22. // Represents a hash table
  23. node *hashtable[N];
  24.  
  25. // Hashes word to a number between 0 and 25, inclusive, based on its first letter
  26. unsigned int hash(const char *word)
  27. {
  28.     return tolower(word[0]) - 'a';
  29. }
  30.  
  31. // Loads dictionary into memory, returning true if successful else false
  32. bool load(const char *dictionary)
  33. {
  34.     // Initialize hash table
  35.     for (int i = 0; i < N; i++)
  36.     {
  37.         hashtable[i] = NULL;
  38.     }
  39.  
  40.     // Open dictionary
  41.     FILE *file = fopen(dictionary, "r");
  42.     if (file == NULL)
  43.     {
  44.         unload();
  45.         return false;
  46.     }
  47.  
  48.     // Buffer for a word
  49.     char word[LENGTH + 1];
  50.  
  51.     // Insert words into hash table
  52.     while (fscanf(file, "%s", word) != EOF)
  53.     {
  54.         // alocate enough memory for a new node
  55.         node * new_node = malloc(sizeof(node));
  56.  
  57.         // Point new node to current first node
  58.         new_node->next = hash(word);
  59.  
  60.         // Point start of node to new node
  61.         hashtable[hash]->next = new_node;
  62.  
  63.         // Add word to new node
  64.         strcpy(new_node->word, word);
  65.     }
  66.  
  67.     // Close dictionary
  68.     fclose(file);
  69.  
  70.     // Indicate success
  71.     return true;
  72. }
  73.  
  74. // Returns number of words in dictionary if loaded else 0 if not yet loaded
  75. unsigned int size(void)
  76. {
  77.     // TODO
  78.     return 0;
  79. }
  80.  
  81. // Returns true if word is in dictionary else false
  82. bool check(const char *word)
  83. {
  84.     // TODO
  85.     return false;
  86. }
  87.  
  88. // Unloads dictionary from memory, returning true if successful else false
  89. bool unload(void)
  90. {
  91.     // TODO
  92.     return false;
  93. }
  94.  

Reply to "I did not bother to name this..."

Here you can reply to the paste above