simple bbolt db in c
#include <simpledb.h>
#include <stdlib.h>
#include <stdint.h>
#include <stdio.h>
int main(){
// open db, pick random slot number if opening multiple db
// can safely use 0 if only one db.
char* err = db_open(42, "foo.db");
if (err) {
printf("fatal: %s\n", (char* )err);
return 1;
}
// reading binary
{
read_response_t resp = db_read(42, "bucketname/nested1/someRandom");
if (resp.error) {
printf("not found? %s\n", resp.data);
} else {
printf("existing data found %lu random bytes we wrote:\n", resp.length);
for (int i = 0; i < resp.length; i++) {
printf("%02x", ((uint8_t*) resp.data)[i]);
}
printf("\n");
fflush(stdout);
}
}
// write anything
{
char buf[32];
FILE *f = fopen("/dev/urandom", "r");
fread(buf, 32, 1, f);
fclose(f);
err = db_write(42, "bucketname/nested1/someRandom", buf, 32);
if (err) {
printf("fatal: %s\n", (char*) err);
return 1;
}
}
// write null-terminated string
{
printf("writing \"foobar!\"\n");
err = db_write_string(42, "bucketname/nested2/someString", "foobar!");
if (err) {
printf("fatal: %s\n", (char*) err);
return 1;
}
}
// reading
{
read_response_t resp = db_read(42, "bucketname/nested2/someString");
if (resp.error) {
printf("fatal: %s\n", resp.data);
return 1;
}
printf("whew! we read the db, found %lu bytes we wrote:\n", resp.length);
for (int i = 0; i < resp.length; i++) {
printf("%c", resp.data[i]);
}
printf("\n");
fflush(stdout);
}
// reading binary
{
read_response_t resp = db_read(42, "bucketname/nested1/someRandom");
if (resp.error) {
printf("fatal: %s\n", resp.data);
return 1;
}
printf("whew! we read the db, found %lu random bytes wrote:\n", resp.length);
for (int i = 0; i < resp.length; i++) {
printf("%02x", ((uint8_t*) resp.data)[i]);
}
printf("\n");
fflush(stdout);
}
// safely close db
err = db_close(42);
if (err) {
printf("fatal: %s\n", (char*) err);
return 1;
}
}