Research portable Memory game | Исследовать портируемую игру Память
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

66 lines
1.7KB

  1. #include <string.h>
  2. #include <stdio.h>
  3. #include "uthash.h"
  4. // this is an example of how to do a LRU cache in C using uthash
  5. // http://troydhanson.github.com/uthash/
  6. // by Jehiah Czebotar 2011 - jehiah@gmail.com
  7. // this code is in the public domain http://unlicense.org/
  8. #define MAX_CACHE_SIZE 50U /* a real value would be much larger */
  9. struct CacheEntry {
  10. char *key;
  11. char *value;
  12. UT_hash_handle hh;
  13. };
  14. struct CacheEntry *cache = NULL;
  15. static void add_to_cache(const char *key, const char *value)
  16. {
  17. struct CacheEntry *entry, *tmp_entry;
  18. entry = (struct CacheEntry *)malloc(sizeof(struct CacheEntry));
  19. if (entry == NULL) {
  20. exit(-1);
  21. }
  22. entry->key = strdup(key);
  23. entry->value = strdup(value);
  24. HASH_ADD_KEYPTR(hh, cache, entry->key, strlen(entry->key), entry);
  25. // prune the cache to MAX_CACHE_SIZE
  26. if (HASH_COUNT(cache) >= MAX_CACHE_SIZE) {
  27. HASH_ITER(hh, cache, entry, tmp_entry) {
  28. // prune the first entry (loop is based on insertion order so this deletes the oldest item)
  29. printf("LRU deleting %s %s\n", entry->key, entry->value);
  30. HASH_DELETE(hh, cache, entry);
  31. free(entry->key);
  32. free(entry->value);
  33. free(entry);
  34. break;
  35. }
  36. }
  37. }
  38. /* main added by Troy D. Hanson */
  39. int main()
  40. {
  41. char linebuf[100];
  42. char nbuf[11];
  43. FILE *file;
  44. unsigned int i=0;
  45. file = fopen( "test65.dat", "r" );
  46. if (file == NULL) {
  47. perror("can't open: ");
  48. exit(-1);
  49. }
  50. while (fgets(linebuf,sizeof(linebuf),file) != NULL) {
  51. snprintf(nbuf,sizeof(nbuf),"%u",i++);
  52. add_to_cache(linebuf, nbuf);
  53. }
  54. fclose(file);
  55. return 0;
  56. }