/** * This is an example of how to write duplicate keys to * a Tokyo Cabinet database (B+Tree API). * * Upon success, this program will generate a file called * "dupkeytext.db" which you should delete afterwards. * * Quick Compile: * $ gcc -std=c99 -Wall -pedantic tc_dupkey.c -ltokyocabinet * * I give up all rights to this code. * * Toru Maesaka */ #include #include #include #include int main(int argc, char **argv) { TCBDB *db; BDBCUR *cursor; const char *key = "key"; const char *r1 = "record 1"; const char *r2 = "record 2"; const char *r3 = "record 3"; if ((db = tcbdbnew()) == NULL) { fprintf(stderr, "failed to create database handle\n"); return 1; } if (!tcbdbopen(db, "dupkeytest.db", BDBOWRITER | BDBOCREAT)) { fprintf(stderr, "failed to open database\n"); return 1; } /* store three different records with the same key */ if (!tcbdbputdup(db, key, 3, r1, strlen(r1)) || !tcbdbputdup(db, key, 3, r2, strlen(r2)) || !tcbdbputdup(db, key, 3, r3, strlen(r3))) { fprintf(stderr, "failed to store data\n"); if (!tcbdbclose(db)) { fprintf(stderr, "failed to close database\n"); return 1; } tcbdbdel(db); return 1; } /* create and prepare the cursor for tree traversal. by meaning "prepare", the cursor will be moved to the first occurrence of the key.*/ if ((cursor = tcbdbcurnew(db)) == NULL) { fprintf(stderr, "failed to create cursor\n"); if (!tcbdbclose(db)) { fprintf(stderr, "failed to close database\n"); return 1; } tcbdbdel(db); return 1; } /* move the cursor to the first occurrence of the key */ if (!tcbdbcurjump(cursor, key, 3)) { fprintf(stderr, "failed to jump the cursor\n"); if (!tcbdbclose(db)) { fprintf(stderr, "failed to close database\n"); return 1; } tcbdbdel(db); return 1; } /* traverse the tree */ char *fetched_key; char *fetched_value; while (tcbdbcurkey2(cursor) != NULL) { fetched_key = tcbdbcurkey2(cursor); if (strcmp(key, fetched_key) != 0) { free(fetched_key); break; } fetched_value = tcbdbcurval2(cursor); if (fetched_value) { fprintf(stdout, "fetched: %s\n", fetched_value); free(fetched_value); } tcbdbcurnext(cursor); } /* free the cursor then cleanup the database for shutdown */ tcbdbcurdel(cursor); if (!tcbdbclose(db)) { fprintf(stderr, "failed to close the database\n"); return 1; } tcbdbdel(db); return 0; }