Skip to content

Instantly share code, notes, and snippets.

@nitingupta910
Forked from crosbymichael/main.c
Last active July 15, 2023 02:58
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nitingupta910/4640638be7e7ad39c41e to your computer and use it in GitHub Desktop.
Save nitingupta910/4640638be7e7ad39c41e to your computer and use it in GitHub Desktop.
rocksdb C example
/*
Makefile:
(make sure Makefile is indented using a tab and not spaces)
all:
cc -Wall -g -O0 rdb_mergeop.c -o rdb_mergeop -lstdc++ -lrocksdb -lsnappy -lbz2 -llz4 -lz
clean:
rm -rf rdb_mergeop
rm -rf testdb
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <rocksdb/c.h>
int main()
{
const char *db_name = "testdb";
rocksdb_options_t *opts = rocksdb_options_create();
rocksdb_options_set_create_if_missing(opts, 1);
rocksdb_options_set_error_if_exists(opts, 1);
rocksdb_options_set_compression(opts, rocksdb_snappy_compression);
char *err = NULL;
rocksdb_t *db = rocksdb_open(opts, db_name, &err);
if (err != NULL) {
fprintf(stderr, "database open %s\n", err);
return -1;
}
free(err);
err = NULL;
rocksdb_writeoptions_t *wo = rocksdb_writeoptions_create();
char *key = "name";
char *value = "foo";
rocksdb_put(db, wo, key, strlen(key), value, strlen(value), &err);
if (err != NULL) {
fprintf(stderr, "put key %s\n", err);
rocksdb_close(db);
return -1;
}
free(err);
err = NULL;
rocksdb_readoptions_t *ro = rocksdb_readoptions_create();
size_t rlen;
value = rocksdb_get(db, ro, key, strlen(key), &rlen, &err);
if (err != NULL) {
fprintf(stderr, "get key %s\n", err);
rocksdb_close(db);
return -1;
}
free(err);
err = NULL;
printf("get key len: %lu, value: %s\n", rlen, value);
rocksdb_close(db);
return 0;
}
@nitingupta910
Copy link
Author

@nikitadanilov
Copy link

err should be initialised to NULL, otherwise the check after rocksdb_open can fail spuriously.

@nitingupta910
Copy link
Author

@nikitadanilov Fixed. Thanks.

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