db3.c
Demonstrates how to use hamsterdb Embedded Storage for sorting large amounts of data
#include <stdio.h>
#include <string.h>
#include <ham/hamsterdb.h>
static int
my_string_compare(ham_db_t *db, const ham_u8_t *lhs, ham_size_t lhs_length,
const ham_u8_t *rhs, ham_size_t rhs_length)
{
(void)db;
return strncmp((const char *)lhs, (const char *)rhs,
lhs_length<rhs_length ? lhs_length : rhs_length);
}
int
main(int argc, char **argv)
{
ham_status_t st;
ham_db_t *db;
ham_cursor_t *cursor;
char line[1024*4];
ham_key_t key;
ham_record_t record;
memset(&key, 0, sizeof(key));
memset(&record, 0, sizeof(record));
printf("This sample uses hamsterdb to sort data.\n");
printf("Reading from stdin...\n");
st=ham_new(&db);
if (st!=HAM_SUCCESS) {
printf("ham_new() failed with error %d\n", st);
return (-1);
}
st=ham_set_compare_func(db, my_string_compare);
if (st) {
printf("ham_set_compare_func() failed with error %d\n", st);
return (-1);
}
st=ham_create(db, "test.db", 0, 0664);
if (st!=HAM_SUCCESS) {
printf("ham_create() failed with error %d\n", st);
return (-1);
}
while (fgets(line, sizeof(line), stdin)) {
char *start=line, *p;
while ((p=strtok(start, " \t\r\n"))) {
key.data=p;
key.size=(ham_size_t)strlen(p)+1;
st=ham_insert(db, 0, &key, &record, 0);
if (st!=HAM_SUCCESS && st!=HAM_DUPLICATE_KEY) {
printf("ham_insert() failed with error %d\n", st);
return (-1);
}
printf(".");
start=0;
}
}
st=ham_cursor_create(db, 0, 0, &cursor);
if (st!=HAM_SUCCESS) {
printf("ham_cursor_create() failed with error %d\n", st);
return (-1);
}
while (1) {
st=ham_cursor_move(cursor, &key, &record, HAM_CURSOR_NEXT);
if (st!=HAM_SUCCESS) {
if (st==HAM_KEY_NOT_FOUND)
break;
else {
printf("ham_cursor_next() failed with error %d\n", st);
return (-1);
}
}
printf("%s\n", (const char *)key.data);
}
st=ham_close(db, HAM_AUTO_CLEANUP);
if (st!=HAM_SUCCESS) {
printf("ham_close() failed with error %d\n", st);
return (-1);
}
ham_delete(db);
return (0);
}