berkdb.c
author Markus Bröker <mbroeker@largo.dyndns.tv>
Fri, 27 Dec 2013 16:00:09 +0100
changeset 167 7c6b221900bf
parent 147 f9015072361f
permissions -rw-r--r--
Proper Datatypes to leave the 80's

/**
 * berkdb.c (C) 2010 Markus Bröker
 *
 */

#include <stdio.h>
#include <stdlib.h>

#include <sys/types.h>
#include <limits.h>
#include <db.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>

DBT key;
DBT data;

/* initialize the db library and open a db file */
DB *dbinit (DB * db, char *filename)
{
    int ret;

    printf ("Initializing berkley db...\n");
    if ((ret = db_create (&db, NULL, 0)) != 0) {
        perror ("db_create");
        return NULL;
    }

    bzero (&key, sizeof (key));
    bzero (&data, sizeof (data));

    printf ("Opening berkdb.db flat database file...\n");
    if ((ret = db->open (db, NULL, filename, NULL, DB_BTREE, DB_CREATE, 0)) != 0) {
        perror ("db->open");
        return NULL;
    }

    return db;
}

/* insert a key/value pair into the database */
int dbinsert (DB * db, int id, char *description)
{
    key.data = &id;
    key.size = sizeof (int);

    data.data = description;
    data.size = strlen (description) + 1;

    return db->put (db, NULL, &key, &data, DB_NOOVERWRITE);
}

/* get the associated value from the database for the key 'id' */
char *dbget (DB * db, int id)
{
    key.data = &id;
    key.size = sizeof (int);

    if (db->get (db, NULL, &key, &data, 0) == 0)
        return (char *)data.data;

    return NULL;
}

/* iterate over the db and print all values */
void dblist (DB * db)
{
    int ret;
    DBC *dbc;

    if (db->cursor (db, NULL, &dbc, 0) != 0) {
        perror ("db->cursor");
        return;
    }

    bzero (&key, sizeof (key));
    while ((ret = dbc->get (dbc, &key, &data, DB_NEXT)) == 0) {
        printf ("KEY[%02d] => %s\n", *(int *)key.data, (char *)data.data);
    }

    if (dbc != NULL) {
        dbc->close (dbc);
    } else
        perror ("dbc");
}

/* close the db */
int dbclose (DB * db)
{
    if (db != NULL) {
        printf ("Closing berkley db file...\n");
        return db->close (db, 0);
    }
    return EXIT_FAILURE;
}

int main (int argc, char **argv)
{
    char description[80];
    int id;

    DB *db = NULL;

    if ((db = dbinit (db, "berkdb.db")) == NULL)
        return EXIT_FAILURE;

    for (id = 0; id < 100; id++) {
        sprintf (description, "This is value %d", id);

        switch (dbinsert (db, id, description)) {
        case 0:
            printf ("KEY ADDED\n");
            break;
        case DB_KEYEXIST:
            printf ("DUPLICATE KEY %d\n", id);
            break;
        default:
            printf ("Error while storing primary key %d\n", id);
        }
    }

    char *value;
    for (id = 0; id < 10; id++) {
        if ((value = dbget (db, id)) != NULL)
            printf ("DB: %s\n", value);
    }

    dblist (db);

    return dbclose (db);
}