Skip to content

Instantly share code, notes, and snippets.

@yowcow
Last active December 6, 2017 01:05
Show Gist options
  • Save yowcow/2539d493f8297738b6bc831852fdcee0 to your computer and use it in GitHub Desktop.
Save yowcow/2539d493f8297738b6bc831852fdcee0 to your computer and use it in GitHub Desktop.
BerkeleyDB cursor in C
#include <stdio.h>
#include <string.h>
#include <db.h>
#define FILE "some.db"
int main() {
DBT key, data;
DBC *cursor;
DB *dbp;
int ret;
ret = db_create(&dbp, NULL, 0);
if (ret != 0) {
printf("db_create() failed");
return 1;
}
ret = dbp->open(dbp, NULL, FILE, NULL, DB_BTREE, DB_RDONLY, 0);
if (ret != 0) {
printf("dbp->open() failed");
return 1;
}
ret = dbp->cursor(dbp, NULL, &cursor, 0);
if (ret != 0) {
printf("dbp->cursor() failed");
return 1;
}
memset(&key, 0, sizeof(DBT));
memset(&data, 0, sizeof(DBT));
key.flags = DB_DBT_REALLOC;
data.flags = DB_DBT_REALLOC;
ret = cursor->c_get(cursor, &key, &data, DB_NEXT);
if (ret != 0) {
printf("cursor->c_get() failed");
return 1;
}
char* k;
k = (char *)key.data;
printf("key: %s\n", k);
printf("size: %d\n", key.size);
free(key.data);
free(data.data);
cursor->c_close(cursor);
dbp->close(dbp, 0);
return 0;
}
@yowcow
Copy link
Author

yowcow commented Dec 5, 2017

==17538== HEAP SUMMARY:
==17538==     in use at exit: 0 bytes in 0 blocks
==17538==   total heap usage: 51 allocs, 51 frees, 35,894 bytes allocated
==17538==
==17538== All heap blocks were freed -- no leaks are possible

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment