diff --git a/.gitignore b/.gitignore index f20737e..695fd6f 100644 --- a/.gitignore +++ b/.gitignore @@ -22,3 +22,4 @@ sophia test-db/ sphia-test-db/ output/ +examples/iteration diff --git a/Makefile b/Makefile index d599474..90c937f 100644 --- a/Makefile +++ b/Makefile @@ -17,6 +17,9 @@ VERSION_MINOR = 1 DEPS = $(shell test -d deps/ && ls deps/) DEP_OBJS = $(wildcard deps/*/*.o) +EXAMPLE_SRCS = $(wildcard examples/*.c) +EXAMPLES = $(EXAMPLE_SRCS:.c=) + TARGET_NAME = lib$(LIB_NAME) TARGET_STATIC = $(TARGET_NAME).a TARGET_DSOLIB = $(TARGET_NAME).so.$(VERSION_MAJOR).$(VERSION_MINOR) @@ -103,6 +106,14 @@ test: $(TEST_OBJS) -lsophia -lpthread @./$(TEST_MAIN) +examples: $(EXAMPLES) +$(EXAMPLES): all + @echo " CC(target) $@.c" + @$(CC) ./$(TARGET_STATIC) \ + -lsophia -lpthread $(CFLAGS) \ + -DSPHIA_TEST_DB='"$(TEST_DB_PATH)"' \ + $@.c -o $(@) + travis: rm -rf sophia git clone --depth=1 https://github.com/pmwkaa/sophia.git sophia @@ -120,12 +131,11 @@ clean: $(TEST_MAIN) $(OBJS) $(TEST_OBJS) $(TARGET_STATIC) \ $(TARGET_DSOLIB) $(TARGET_DSO).$(VERSION_MAJOR) \ $(TARGET_DSO) $(TARGET_DYLIB) $(TEST_DB_PATH) \ - test-db sophia output; do \ + $(EXAMPLES) test-db sophia output; do \ echo " RM $$item"; \ $(RM) -rf $$item; \ done; - install: all test -d $(PREFIX)/$(DESTDIR) || mkdir $(PREFIX)/$(DESTDIR) install $(LIB_NAME).h $(PREFIX)/include @@ -138,4 +148,4 @@ uninstall: rm -f $(PREFIX)/lib/$(TARGET_STATIC) rm -f $(PREFIX)/lib/$(TARGET_DSO) -.PHONY: test deps +.PHONY: test deps examples diff --git a/examples/iteration.c b/examples/iteration.c new file mode 100644 index 0000000..e2dc58f --- /dev/null +++ b/examples/iteration.c @@ -0,0 +1,45 @@ + +#include +#include + +#define error_and_exit() { \ + fprintf(stderr, "error: %s\n", sphia_error(sphia)); \ + exit(1); \ +} + + +int +main (void) { + sphia_t *sphia = sphia_new(SPHIA_TEST_DB); + if (NULL == sphia) error_and_exit(); + + // set 100 key/value pairs, just for something to iterate + for (int i = 0; i < 100; i++) { + char *key = malloc(16); + char *value = malloc(16); + + sprintf(key, "key%03d", i); + sprintf(value, "value%03d", i); + + if (-1 == sphia_set(sphia, key, value)) error_and_exit(); + } + + // create our iterator + sphia_iterator_t *iterator = sphia_iterator_new(sphia); + if (NULL == iterator) error_and_exit(); + + sphia_iterator_node_t *node; + // loop until we hit the end + while ((node = sphia_iterator_next(iterator))) { + printf("%s = '%s'\n", node->key, node->value); + // cleanup the node + sphia_iterator_node_free(node); + } + + // close the iterator + sphia_iterator_free(iterator); + + // close the db + sphia_free(sphia); + return 0; +}