Utilizing Gdbm, GNU's Easy-to-Use Database Management Library
Adding Data
Data is stored in gdbm files by means of key/value pairs. The "key" is analogous to a data string's name, and the "value" (or "content") is, of course, your data. So, for example, you might have a key called "name," and the content would be "John Smith." Here's how you add a record:
ret = gdbm_store(dbf, key, content, flag); |
Both the "key" and the "content" arguments are of type "datum," which is defined by this structure:
typedef struct { char *dptr; int dsize; } datum; |
The "flag" argument tells gdbm what to do if the "key" you're adding already exists. (Of course, if it doesn't yet exist, then there's no problem.) The two options for the flag are:
GDBM_REPLACE -- Trash the old data, and replace it with the new. GDBM_INSERT -- Only add the data if it won't overwrite anything else. If a key with the same name already exists, then return an error (without writing anything). |
Then, as you've probably guessed, "ret" is your return value. Here are the three possible outcomes:
-1 The data was NOT stored, because the database was opened in read-only mode, or the data was NULL. 1 The data was NOT stored, because the "flag" used was GDBM_INSERT and a key with the same name was already in the database. 0 The data was written successfully. |
So, anything other than a zero means "no dice."
Retrieving Data
Now that you've populated your database, how do you get the information back out? Simple! Use gdbm_fetch(), like this:
content = gdbm_fetch(dbf, key); |
Now, as I said, gdbm databases aren't indexed, so it's conceivable that your fetch will have to read through the entire database before it finds your key. This is why gdbm isn't the best choice for, say, the telephone records of the entire eastern seaboard. Nevertheless, gdbm's simplicity can't be beat. If you merely want to see if a record exists (without reading it), use:
ret = gdbm_exists(dbf, key); |
Trashing Records
If you want to delete a record without replacing it, just use gdbm_delete() as follows:
ret = gdbm_delete(dbf, key); |
Retrieving ALL Records
If you want each and every piece of data in your database, you can use the next two functions:
key = gdbm_firstkey(dbf); nextkey = gdbm_nextkey(dbf, key); |
Keep calling gdbm_nextkey(),until you get a NULL value, indicating that you've reached the end of the database.
Page 2 of 3
This article was originally published on January 4, 2001