db5.c
Demonstrates the use of duplicate items; reads a text file from stdin and creates a Database entry for every word, even if the word is a duplicate. Then prints all words in alphabetical order and prints the line number of each occurrence.
#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];
unsigned lineno=0;
ham_key_t key;
ham_record_t record;
memset(&key, 0, sizeof(key));
memset(&record, 0, sizeof(record));
printf("This sample uses hamsterdb and duplicate keys to list all words "
"in the\noriginal order, together with their line number.\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_ENABLE_DUPLICATES, 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;
lineno++;
while ((p=strtok(start, " \t\r\n"))) {
key.data=p;
key.size=(ham_size_t)strlen(p)+1;
record.data=&lineno;
record.size=sizeof(lineno);
st=ham_insert(db, 0, &key, &record, HAM_DUPLICATE);
if (st!=HAM_SUCCESS) {
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: appeared in line %u\n", (const char *)key.data,
*(unsigned *)record.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);
}