Advertisement
Jodyone

optimized load

Oct 24th, 2014
191
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.65 KB | None | 0 0
  1. bool load(const char* dictionary)
  2. {
  3.     // TODO
  4.     // do some prep work
  5.    
  6.        struct stat buf;
  7.     if (stat(dictionary,&buf))
  8.         return false;
  9.  
  10.     // map file into memory
  11.     int fd = open(dictionary, O_RDONLY);
  12.     if (fd < 0)
  13.         return false;
  14.    
  15.     char *map = mmap(0, buf.st_size, PROT_READ, MAP_SHARED, fd, 0);
  16.     if (map == MAP_FAILED)
  17.     {
  18.         close(fd);
  19.         return false;
  20.     }
  21.  
  22.        // start = &map[0];
  23.        // this is a pointer to point at the first character in the string
  24.        char* start = map;
  25.  
  26.        // end = start;
  27.        // this is a pointer to mark the end of the string \n
  28.        char* end = start;
  29.  
  30.        // loop to advance "end" until it points to a newline
  31.        for (char* i = end; *i < sizeof(buf.st_size); i++)
  32.        {
  33.            // check if i is \n
  34.            if ( *i == '\n')
  35.            {
  36.                 //start is now a pointer to a null terminated string!
  37.                 // place that pointer into the node
  38.                 node* new_node = malloc(sizeof(node));
  39.                 new_node->next = NULL;
  40.                 new_node->word = start;
  41.                 //place the node into the hashtable
  42.                 int x = hash_d(new_node->word);
  43.                 new_node->next = hashtable[x];
  44.                 hashtable[x] = new_node;
  45.                 // set start to point one character after end, so it points to the start of the next string
  46.                 start = &end[*i + 1];
  47.            }
  48.             // repeat until you have processed all the strings
  49.         }
  50.        
  51.        
  52.        
  53.        
  54.     // do some cleanup work
  55.     close(fd);
  56.     return true;
  57.  }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement