Topic: gdbm -- Example code

up to gdbm index ]
This example code is pretty simple, but it's the sort of thing I like to study to get a start in something, so here it is in all its tepid glory. All it does is to open a gdbm file specified on the command line, fetch a key, and display the key.
#include <stdio.h>
#include <string.h>
#include <gdbm.h>

GDBM_FILE dbf;
datum key, data;

main (int argc, char *argv[])
{
   if (argc < 3)
      fprintf (stderr, "Usage: dbmexample  \n\n");
      exit (1);
   }

   dbf = gdbm_open (argv[1], 0, GDBM_READER, 0666, 0);
   if (!dbf)
   {
      fprintf (stderr, "File %s either doesn't exist or is not a gdbm file.\n", argv[1]);
      exit (2);
   }

   key.dsize = strlen (argv[2]) + 1;

   data = gdbm_fetch (dbf, key);

   if (data.dsize > 0) {
      printf ("%s\n", data.dptr);
      free (data.dptr);
   } else {
      printf ("Key %s not found.\n", argv[2]);
   }
   gdbm_close (file);
}
A couple of notes on this little program:
  • I'm assuming that the process which wrote the key and data included the terminating null character. Gdbm in general doesn't have to do that, which is why there's a dsize element in the datum structure. But for most C applications, of course, it's pretty darned convenient to have that null there. So you can see that key.dsize is one larger than the length of argv[2], and that's to include the null. Note that if the reader and writer don't use the same terminating null convention, then the keys don't match! That null is really part of the key, and fetching without it won't find the proper record.
  • The second parameter of gdbm_open is the retrieval block size of the file. If less than 256, the system stat size will be used, and I figure that's safe. If somebody can tell me a little about tuning using this parameter, I'd appreciate it.
  • Sorry that the example is so minimal. It really is just intended to get you started.
  • At least on Solaris, you can compile this example by using:
    gcc example.c -lgdbm





Copyright © 1996-2007 Vivtek. All Rights Reserved. Read the disclaimer.
Read our privacy statement, too, if you are concerned.