1. Prototypes

1.1. proto_gdbm.cc


1.1.1

A program to dump a list of words and their ID numbers from the database produced by `man_index' into a GDBM hash table. This could also be made to work with DBM or NDBM, which might be more portable.


1.1.2
#include <cstring>
#include <cstdio>
#include <gdbm.h>

1.1.3

The path to the directory in which the DB will be created. The path and all of the filenames are hardcoded for simplicity.

#define DB_DIR "/tmp"

1.1.4

The main (and only) function. No command line arguments are needed.

int
main ()
{

1.1.5

Create a new database file (or open an existing one, but that isn't what is intended here). We will only be writting to it.

   GDBM_FILE db = gdbm_open (DB_DIR "/qef_test_gdbm", 0, GDBM_WRITER, 0700, NULL);

1.1.6

Open the file which was created by `man_index'.

   FILE *f = fopen (DB_DIR "/man_words", "r");

1.1.7

Buffers to store the name and ID number read from each line.

   char name[4096];
   char idstr[64];

1.1.8

The line number is counted so that it can be used in error messages.

   unsigned int line_num = 1;

1.1.9

Read lines from the word list. Each line is expected to contain a word and its unique ID number, seperated by whitespace.

   int rc;
   while ((rc = fscanf (f, "%s %s", name, idstr)) == 2)
   {

1.1.10

Create new `datum' objects to add with the word as the key and the ID number as the value, which is how this would be used if it was for real.

      datum dnam, did;
      dnam.dptr = name;
      dnam.dsize = strlen (name);
      did.dptr = idstr;
      did.dsize = strlen (idstr);

1.1.11

Stick it in the DB.

      if (gdbm_store (db, dnam, did, GDBM_REPLACE))
         fprintf (stderr, "Error writing value to DBM file.\n");

      ++line_num;
   }

1.1.12

Check the loop wasn't terminated because of a formatting error in the input file.

   if (rc ≠ EOF)
      fprintf (stderr, "%d: For some reason fscanf returned `%d'.\n",
               line_num, rc);

1.1.13

Close the DB nicely.

   gdbm_close (db);
   return 0;
}