3.2. gdbm_list.cc
A little utility to list the records in a GDBM file to the standard output.
The only command line argument is the name of the file. The records are
not guaranteed to come out in any particular order.
#include "doc.hh"
#include <cstring>
#include <cstdio>
#include <cstdlib>
#include <gdbm.h>
Create a dynamically allocated and nicely escapped copy of the string in a
`datum' object.
void
copy_datum_str (const datum &d, string &s)
{
const char *hexdigits = "0123456789ABCDEF";
for (size_t i = 0; i < d.dsize; ++i)
{
char c = d.dptr[i];
if (c == '\\')
s += "\\\\";
else if (c == ':')
s += "\\:";
else if (c ≥ 32 && c < 127)
s += c;
else
{
switch (c)
{
case '\a': s += "\\a"; break;
case '\b': s += "\\b"; break;
case '\t': s += "\\t"; break;
case '\n': s += "\\n"; break;
case '\v': s += "\\v"; break;
case '\f': s += "\\f"; break;
case '\r': s += "\\r"; break;
case 27: s += "\\e"; break;
default:
s += "\\x";
s += hexdigits[(c / 16) & 0x0F];
s += hexdigits[c & 0x0F];
}
}
}
}
The main function.
int
main (int argc, char **argv)
{
Check command line arguments.
if (argc ≠ 2)
{
fprintf (stderr, "Usage: %s FILENAME\n", argv[0]);
return 1;
}
Try to open the file.
GDBM_FILE db = gdbm_open (argv[1], 0, GDBM_READER, 0600, NULL);
if (db == NULL)
{
fprintf (stderr, "%s: unable to open GDBM file `%s': %s\n",
argv[0], argv[1], gdbm_strerror (gdbm_errno));
return 2;
}
Sequence through the records and print them out.
datum key = gdbm_firstkey (db);
while (key.dptr)
{
datum val = gdbm_fetch (db, key);
string keystr, valstr;
copy_datum_str (key, keystr);
copy_datum_str (val, valstr);
printf ("%s:%s\n", keystr.c_str(), valstr.c_str());
datum nextkey = gdbm_nextkey (db, key);
free (key.dptr);
free (val.dptr);
key = nextkey;
}
Close the DB nicely and finish.
gdbm_close (db);
return 0;
}