sdb_cats.c 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. /*
  2. * This program is free software; you can redistribute it and/or
  3. * modify it under the terms of the GNU General Public License
  4. * as published by the Free Software Foundation; either version 2
  5. * of the License, or (at your option) any later version.
  6. *
  7. * This program is distributed in the hope that it will be useful,
  8. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. * GNU General Public License for more details.
  11. * Author: hakanai
  12. */
  13. #include <stdio.h>
  14. #include <assert.h>
  15. #include <string.h>
  16. #include <libsdb.h>
  17. #include <unistd.h>
  18. #define TFILE "/tmp/d23rnst39ax.sdb"
  19. #define CATS "./cat_names.txt"
  20. struct record_t {
  21. int num;
  22. char str[48];
  23. };
  24. static void populate_db(sdb_t *db) {
  25. struct record_t r = { 0 };
  26. uint16_t size = sizeof(struct record_t);
  27. FILE *fd = fopen(CATS, "r");
  28. char name[48];
  29. assert(fd != NULL);
  30. while (fgets(name, 48, fd)) {
  31. memset(&r, 0, size);
  32. strncpy(r.str, name, (strlen(name) - 1));
  33. assert(sdb_append(db, &r, size) == SDB_OK);
  34. }
  35. fclose(fd);
  36. }
  37. static void print_cats(sdb_t *db) {
  38. struct record_t r = { 0 };
  39. int size = sdb_size(db);
  40. for (int i = 0; i < size; i++) {
  41. assert(sdb_read(db, i, &r) == SDB_OK);
  42. }
  43. }
  44. static void remove_all_W(sdb_t *db) {
  45. struct record_t r = { 0 };
  46. int size = sdb_size(db);
  47. int i;
  48. for (i = 0; i < size; i++) {
  49. assert(sdb_read(db, i, &r) == SDB_OK);
  50. if (r.str[0] == 'W') {
  51. puts(r.str);
  52. assert(sdb_delete(db, i) == SDB_OK);
  53. size--;
  54. i--;
  55. }
  56. }
  57. strncpy(r.str, "None", 4);
  58. assert(sdb_update(db, i, &r) == SDB_OK);
  59. }
  60. static int test_cats() {
  61. struct record_t r, b;
  62. uint16_t size = sizeof(struct record_t);
  63. sdb_t db;
  64. assert(sdb_open(TFILE, &db) == SDB_OK);
  65. populate_db(&db);
  66. print_cats(&db);
  67. remove_all_W(&db);
  68. sdb_close(&db);
  69. unlink(TFILE);
  70. return 0;
  71. }
  72. int main() {
  73. unlink(TFILE);
  74. assert(!test_cats());
  75. return 0;
  76. }