db4.c
Demonstrates the use of Record Number Databases; reads a text file from stdin and creates a Database entry for every word. Then prints all words in the original order.
#include <stdio.h>
#include <string.h>
#include <ham/hamsterdb.h>
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 list all words in the "
"original order.\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_create(db, "test.db", HAM_RECORD_NUMBER, 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"))) {
ham_u64_t recno;
key.flags=HAM_KEY_USER_ALLOC;
key.data=&recno;
key.size=sizeof(recno);
record.data=p;
record.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);
}
}
#if WIN32
printf("%I64u: %s\n", *(ham_u64_t *)key.data,
(const char *)record.data);
#else
printf("%llu: %s\n", *(unsigned long long *)key.data,
(const char *)record.data);
#endif
}
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);
}