C/C++ Programming Pearls

Example 1
/*
  Examples for C api interface for Berkerley DB
  There are a few changes from the http://www.sleepycat.com
  
  To complile:
	gcc -ldb -o dbcreate dbcreate.c





*/



#include <sys/types.h>
#include <stdlib.h>
#include <stdio.h>
#include <db.h>

#define DATABASE "access.db"

int
main()
{
  DB *dbp;
  DBT key, data;
  int ret, t_ret;

  if ((ret = db_create(&dbp, NULL, 0)) != 0) {
    fprintf(stderr, "db_create: %s\n", db_strerror(ret));
    exit (1);
  }


  if ((ret = dbp->open(dbp, DATABASE, NULL, DB_BTREE, DB_CREATE, 0664)) != 0) {
    dbp->err(dbp, ret, "%s", DATABASE);
    goto err;

  }

  /* clearing memory before use */
  memset(&key, 0, sizeof(key));
  memset(&data, 0, sizeof(data));

  key.data = "fruit";
  key.size = sizeof("fruit");
  printf("sizeof(\"fruit\")=%d  Note this includes null value as well \n",sizeof("fruit"));
  data.data = "apple";
  data.size = sizeof("apple");


  switch (ret =
	  dbp->put(dbp, NULL, &key, &data, DB_NOOVERWRITE)) {
  case 0:
    printf("db: %s: key stored.\n", (char *)key.data);
    break;
  case DB_KEYEXIST:
    printf("db: %s: key previously stored.\n",
	   (char *)key.data);
    break;
  default:
    dbp->err(dbp, ret, "DB->put");
    fprintf(stderr,"Error In putting in keys \n");
    goto err;
  }





  key.data = "auto";
  key.size = sizeof("auto");
  data.data = "vw bug";
  data.size = sizeof("vw bug");



  switch (ret =
	  dbp->put(dbp, NULL, &key, &data, DB_NOOVERWRITE)) {
  case 0:
    printf("db: %s: key stored.\n", (char *)key.data);
    break;
  case DB_KEYEXIST:
    printf("db: %s: key previously stored.\n",
	   (char *)key.data);
    break;
  default:
    dbp->err(dbp, ret, "DB->put");
    fprintf(stderr,"Error In putting in keys \n");
    goto err;
  }





  key.data = "fruit";
  key.size = sizeof("fruit");




  if ((ret = dbp->get(dbp, NULL, &key, &data, 0)) == 0)
    printf("db: %s: key retrieved: data was %s.\n",
	   (char *)key.data, (char *)data.data);
  else {
    dbp->err(dbp, ret, "DB->get");
    fprintf(stderr,"Error retrieving data \n");
    goto err;

  }


  /* Deleting a key data pair */

  if ((ret = dbp->del(dbp, NULL, &key, 0)) == 0)
    printf("db: %s: key was deleted.\n", (char *)key.data);
  else {
    dbp->err(dbp, ret, "DB->del");
    goto err;
  }





  /* If you forget to close the database, then, the values
     will not be stored */

 err:  if ((t_ret = dbp->close(dbp, 0)) != 0 && ret == 0)
          ret = t_ret; 

    



}


Notes
SourceForge.net Logo