     [file version.texi not included]

This file documents the GNU dbm utility.

Copyright © 1989-1999, 2007, 2008, 2009-2011 Free Software Foundation, Inc.

Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.3 or any later version published by the Free Software Foundation; with no Invariant Sections, with the Front-Cover Texts being ``The GNU Database Manager,'' and with the Back-Cover Texts as in (a) below.  A copy of the license is included in the section entitled ``GNU Free Documentation License.''

(a) The FSF's Back-Cover Text is: ``You have the freedom to copy and modify this GNU manual.  Buying copies from the FSF supports it in developing GNU and promoting software freedom.''

The GNU database manager.
*************************

GNU dbm is a library of functions implementing a hashed database on a disk file.  This manual documents GNU dbm Version VERSION (gdbm).  The software was originally written by Philip A.  Nelson.  This document was originally written by Pierre Gaumond from texts written by Phil.

Copying Conditions.
*******************

This library is free; this means that everyone is free to use it and free to redistribute it on a free basis.  GNU dbm (gdbm) is not in the public domain; it is copyrighted and there are restrictions on its distribution, but these restrictions are designed to permit everything that a good cooperating citizen would want to do.  What is not allowed is to try to prevent others from further sharing any version of gdbm that they might get from you.

Specifically, we want to make sure that you have the right to give away copies gdbm, that you receive source code or else can get it if you want it, that you can change these functions or use pieces of them in new free programs, and that you know you can do these things.

To make sure that everyone has such rights, we have to forbid you to deprive anyone else of these rights.  For example, if you distribute copies gdbm, you must give the recipients all the rights that you have.  You must make sure that they, too, receive or can get the source code.  And you must tell them their rights.

Also, for our own protection, we must make certain that everyone finds out that there is no warranty for anything in the gdbm distribution. If these functions are modified by someone else and passed on, we want their recipients to know that what they have is not what we distributed, so that any problems introduced by others will not reflect on our reputation.

Gdbm is currently distributed under the terms of the GNU General Public License, Version 3.  (NOT under the GNU General Library Public License.)  A copy the GNU General Public License is included with the distribution of gdbm.

Introduction to GNU dbm.
************************

GNU dbm (gdbm) is a library of database functions that use extensible hashing and works similar to the standard UNIX dbm functions.  These routines are provided to a programmer needing to create and manipulate a hashed database. (gdbm is NOT a complete database package for an end user.)

The basic use of gdbm is to store key/data pairs in a data file. Each key must be unique and each key is paired with only one data item. The keys can not be directly accessed in sorted order.  The basic unit of data in gdbm is the structure:

       typedef struct {
                  char *dptr;
                  int  dsize;
               } datum;

This structure allows for arbitrary sized keys and data items.

The key/data pairs are stored in a gdbm disk file, called a gdbm database.  An application must open a gdbm database to be able manipulate the keys and data contained in the database. gdbm allows an application to have multiple databases open at the same time.  When an application opens a gdbm database, it is designated as a reader or a writer.  A gdbm database can be opened by at most one writer at a time.  However, many readers may open the database simultaneously.  Readers and writers can not open the gdbm database at the same time.

List of functions.
******************

The following is a quick list of the functions contained in the gdbm library.  The include file gdbm.h, that can be included by the user, contains a definition of these functions.

     #include <gdbm.h>

     GDBM_FILE gdbm_open(name, block_size, flags, mode, fatal_func);
     void gdbm_close(dbf);
     int gdbm_store(dbf, key, content, flag);
     datum gdbm_fetch(dbf, key);
     int gdbm_delete(dbf, key);
     datum gdbm_firstkey(dbf);
     datum gdbm_nextkey(dbf, key);
     int gdbm_reorganize(dbf);
     void gdbm_sync(dbf);
     int gdbm_exists(dbf, key);
     char *gdbm_strerror(errno);
     int gdbm_setopt(dbf, option, value, size);
     int gdbm_fdesc(dbf);

The gdbm.h include file is often in the /usr/local/include directory. (The actual location of gdbm.h depends on your local installation of gdbm.)

Opening the database.
*********************

 -- gdbm interface: GDBM_FILE gdbm_open (const char *NAME, int BLOCK_SIZE,
     int FLAGS, int MODE, void (*fatal_func)(const char *))
     Initializes gdbm system.  If the file has a size of zero bytes, a file initialization procedure is performed, setting up the initial structure in the file.

     The arguments are:

     name
          The name of the file (the complete name, gdbm does not append any characters to this name).

     block_size
          It is used during initialization to determine the size of various constructs.  It is the size of a single transfer from disk to memory.  This parameter is ignored if the file has been previously initialized.  The minimum size is 512.  If the value is less than 512, the file system block size is used, otherwise the value of BLOCK_SIZE is used.

     flags
          If flags is set to GDBM_READER, the user wants to just read the database and any call to gdbm_store or gdbm_delete will fail. Many readers can access the database at the same time.  If flags is set to GDBM_WRITER, the user wants both read and write access to the database and requires exclusive access.  If flags is set to GDBM_WRCREAT, the user wants both read and write access to the database and wants it created if it does not already exist.  If flags is set to GDBM_NEWDB, the user want a new database created, regardless of whether one existed, and wants read and write access to the new database.

          The following may also be logically or'd into the database flags: GDBM_SYNC, which causes all database operations to be synchronized to the disk, GDBM_NOLOCK, which prevents the library from performing any locking on the database file, and GDBM_NOMMAP, which disables the memory mapping mechanism.  The option GDBM_FAST is now obsolete, since gdbm defaults to no-sync mode.  Any error detected will cause a return value of NULL and an appropriate value will be in gdbm_errno (see Variables).  If no errors occur, a pointer to the gdbm file descriptor will be returned.

     mode
          File mode (see change permissions of a file (chmod(2) man page), and see open a file (open(2) man page)), which is used if the file is created).

     fatal_func
          A function for gdbm to call if it detects a fatal error.  The only parameter of this function is a string.  If the value of NULL is provided, gdbm will use a default function.

     The return value, is the pointer needed by all other functions to access that gdbm file.  If the return is the NULL pointer, gdbm_open was not successful.  The errors can be found in gdbm_errno variable (see gdbm_errno).  Available error codes are discussed in Error codes.

     In all of the following calls, the parameter DBF refers to the pointer returned from gdbm_open.

Closing the database.
*********************

It is important that every file opened is also closed.  This is needed to update the reader/writer count on the file:

 -- gdbm interface: void gdbm_close (GDBM_FILE DBF)
     This function closes the gdbm file and frees all memory associated with it.  The parameter is:

     dbf
          The pointer returned by gdbm_open.

Inserting and replacing records in the database.
************************************************

 -- gdbm interface: int gdbm_store (GDBM_FILE DBF, datum KEY,
     datum CONTENT, int FLAG)
     The function gdbm_store inserts or replaces records in the database.

     The parameters are:

     dbf
          The pointer returned by gdbm_open.

     key
          The search key.

     content
          The data to be associated with the key.

     flag
          Defines the action to take when the key is already in the database.  The value GDBM_REPLACE (defined in gdbm.h) asks that the old data be replaced by the new CONTENT.  The value GDBM_INSERT asks that an error be returned and no action taken if the KEY already exists.

     This function can return the following values:

     -1
          The item was not stored in the database because the caller was not an official writer or either KEY or CONTENT have a NULL dptr field.

          Both KEY and CONTENT must have the dptr field be a non-NULL value.  Since a NULL dptr field is used by other functions to indicate an error, it cannot be valid data.

     +1
          The item was not stored because the argument FLAG was GDBM_INSERT and the KEY was already in the database.

     0
          No error.  The value of CONTENT is keyed by KEY.  The file on disk is updated to reflect the structure of the new database before returning from this function.

If you store data for a KEY that is already in the data base, gdbm replaces the old data with the new data if called with GDBM_REPLACE.  You do not get two data items for the same key and you do not get an error from gdbm_store.

The size in gdbm is not restricted like dbm or ndbm.  Your data can be as large as you want.

Searching for records in the database.
**************************************

 -- gdbm interface: datum gdbm_fetch (GDBM_FILE DBF, datum KEY)
     Looks up a given KEY and returns the information associated with it. The dptr field in the structure that is returned points to a memory block allocated by malloc.  It is the caller's responsibility to free it when no longer needed.

     If the dptr is NULL, no data was found.

     The parameters are:

     dbf
          The pointer returned by gdbm_open.

     key
          The search key.

An example of using this function:

     content = gdbm_fetch (dbf, key);
     if (content.dptr == NULL)
       {
         fprintf(stderr, "key not found\n");
       }
     else
       {
         /* do something with content.dptr */
       }

You may also search for a particular key without retrieving it:

 -- gdbm interface: int gdbm_exists (GDBM_FILE DBF, datum KEY)
     Returns true (1) if the KEY exists in DBF and false (0) otherwise.

     The parameters are:

     dbf
          The pointer returned by gdbm_open.

     key
          The search key.

Removing records from the database.
***********************************

To remove some data from the database, use the gdbm_delete function.

 -- gdbm interface: int gdbm_delete (GDBM_FILE DBF, datum KEY)
     Deletes the data associated with the given KEY, if it exists in the database DBF.  The file on disk is updated to reflect the structure of the new database before returning from this function.

     The parameters are:

     dbf
          The pointer returned by gdbm_open.

     datum key
          The search key.

     The function returns -1 if the item is not present or the requester is a reader.  The return of 0 marks a successful delete.

Sequential access to records.
*****************************

The next two functions allow for accessing all items in the database.  This access is not key sequential, but it is guaranteed to visit every key in the database once.  The order has to do with the hash values. gdbm_firstkey starts the visit of all keys in the database. gdbm_nextkey finds and reads the next entry in the hash structure for dbf.

 -- gdbm interface: datum gdbm_firstkey (GDBM_FILE DBF)
     Initiate sequential access to the database DBF.  The returned value is the first key accessed in the database.  If the dptr field in the returned datum is NULL, the database contains no data.

     Otherwise, dptr points to a memory block obtained from malloc, which holds the key value.  The caller is responsible for freeing this memory block when no longer needed.

 -- gdbm interface: datum gdbm_nextkey (GDBM_FILE DBF, datum PREV)
     This function continues the iteration over the keys in DBF, initiated by gdbm_firstkey.  The parameter PREV holds the value returned from a previous call to gdbm_nextkey or gdbm_firstkey.

     The function returns next key from the database.  If the dptr field in the returned datum is NULL, all keys in the database has been visited.

     Otherwise, dptr points to a memory block obtained from malloc, which holds the key value.  The caller is responsible for freeing this memory block when no longer needed.

These functions were intended to visit the database in read-only algorithms, for instance, to validate the database or similar operations.  The usual algorithm for sequential access is:

        key = gdbm_firstkey (dbf);
        while (key.dptr)
          {
             datum nextkey;

             /* do something with the key */
             ...

             /* Obtain the next key */
             nextkey = gdbm_nextkey (dbf, key);
             /* Reclaim the memory used by the key */
             free (key.dptr);
             /* Use nextkey in the next iteration. */
             key = nextkey;
          }

Care should be taken when the gdbm_delete function is used in such a loop.  File visiting is based on a hash table.  The gdbm_delete function re-arranges the hash table to make sure that any collisions in the table do not leave some item un-findable.  The original key order is not guaranteed to remain unchanged in all instances.  So it is possible that some key will not be visited if a loop like the following is executed:

        key = gdbm_firstkey (dbf);
        while (key.dptr)
          {
             datum nextkey;
             if (some condition)
               {
                  gdbm_delete (dbf, key);
               }
              nextkey = gdbm_nextkey (dbf, key);
              free (key.dptr);
              key = nextkey;
           }

Database reorganization.
************************

The following function should be used very seldom.

 -- gdbm interface: int gdbm_reorganize (GDBM_FILE DBF)
     Reorganizes the database.

     The parameter is:

     dbf
          The pointer returned by gdbm_open.

If you have had a lot of deletions and would like to shrink the space used by the gdbm file, this function will reorganize the database. This results, in particular, in shortening the length of a gdbm file by removing the space occupied by deleted records.

This reorganization requires creating a new file and inserting all the elements in the old file DBF into the new file.  The new file is then renamed to the same name as the old file and DBF is updated to contain all the correct information about the new file.  If an error is detected, the return value is negative.  The value zero is returned after a successful reorganization.

Database Synchronization
************************

Unless your database was opened with the GDBM_SYNC flag, gdbm does not wait for writes to be flushed to the disk before continuing.  This allows for faster writing of databases at the risk of having a corrupted database if the application terminates in an abnormal fashion.  The following function allows the programmer to make sure the disk version of the database has been completely updated with all changes to the current time.

 -- gdbm interface: void gdbm_sync (GDBM_FILE DBF)
     Synchronizes the changes in DBF with its disk file.  The parameter is a pointer returned by gdbm_open.

     This function would usually be called after a complete set of changes have been made to the database and before some long waiting time. The gdbm_close function automatically calls the equivalent of gdbm_sync so no call is needed if the database is to be closed immediately after the set of changes have been made.

Export and Import
*****************

Gdbm databases can be converted into a portable flat format.  This format can be used, for example, to migrate between the different versions of gdbm databases.  Generally speaking, flat files are safe to send over the network, and can be used to recreate the database on another machine.  The recreated database is guaranteed to be a byte-to-byte equivalent of the database from which the flat file was created.  This does not necessarily mean, however, that this file can be used in the same way as the original one.  For example, if the original database contained non-ASCII data (e.g.  C structures, integers etc.), the recreated database can be of any use only if the target machine has the same integer size and byte ordering as the source one and if its C compiler uses the same packing conventions as the one which generated C which populated the original database.  In general, such binary databases are not portable between machines, unless you follow some stringent rules on what data is written to them and how it is interpreted.

 -- gdbm interface: int gdbm_export (GDBM_FILE DBF,
     const char *EXPORTFILE, int FLAG, int MODE)
     Create a flat file from the gdbm database.  The parameters are:

     dbf
          A pointer to the source database, returned by a call to gdbm_open.  The database must be open in GDBM_WRITER mode.

     exportfile
          The name of the output file.

     flag
          How to create the output file.  If FLAG is GDBM_WRCREAT, the file will be created if it does not exist already.  Otherwise, if it is GDBM_NEWDB, it will be created if it does not exist, and truncated otherwise.

     mode
          The permissions to use when creating the output file. See http://www.manpagez.com/man/2/open,

          open a file (open(2) man page), for a detailed discussion.

 -- gdbm interface: int gdbm_import (GDBM_FILE DBF,
     const char *IMPORTFILE, int FLAG)
     Populates the database from an existing flat file.

     dbf
          A pointer to the source database, returned by a call to gdbm_open.  The database must be open in GDBM_WRITER mode.

     importfile
          The name of the input flat file.  The file must exist.

     flag
          The FLAG argument to be passed to gdbm_store function when adding new records.  See Store, for a description of its effect.

See also gdbmexport, testgdbm export, and testgdbm import.

Error strings.
**************

To convert a gdbm error code into English text, use this routine:

 -- gdbm interface: const char * gdbm_strerror (gdbm_error ERRNO)
     Converts ERRNO (which is an integer value) into a human-readable descriptive text.  Returns a pointer to a static string.  The caller must not alter or free the returned pointer.

     The ERRNO argument is usually the value of the global variable gdbm_errno.  See gdbm_errno.

Setting options
***************

Gdbm supports the ability to set certain options on an already open database.

 -- gdbm interface: int gdbm_setopt (GDBM_FILE DBF, int OPTION,
     void *VALUE, int SIZE)
     Sets an option on the database.

     The parameters are:

     dbf
          The pointer returned by gdbm_open.

     option
          The option to be set.

     value
          A pointer to the value to which OPTION will be set.

     size
          The length of the data pointed to by VALUE.

The valid options are:

GDBM_CACHESIZE
     Set the size of the internal bucket cache.  This option may only be set once on each GDBM_FILE descriptor, and is set automatically to 100 upon the first access to the database.  The VALUE should point to an integer holding the desired cache size.

GDBM_FASTMODE
     Enable or disable the fast writes mode, i.e. writes without subsequent synchronization.  The VALUE should point to an integer: TRUE to enable fast mode, and FALSE to disable it.

     This option is retained for compatibility with previous versions of gdbm.  Its effect is the reverse of GDBM_SYNCMODE (see below).

GDBM_SYNCMODE
     Turn on or off file system synchronization operations.  This setting defaults to off.  The VALUE should point to an integer: TRUE to turn synchronization on, and FALSE to turn it off.

     Note, that this option is a reverse of GDBM_FASTMODE, i.e. calling GDBM_SYNCMODE with TRUE has the same effect as calling GDBM_FASTMODE with FALSE.

GDBM_CENTFREE
     NOTICE: This feature is still under study.

     Set central free block pool to either on or off.  The default is off, which is how previous versions of gdbm handled free blocks.  If set, this option causes all subsequent free blocks to be placed in the global pool, allowing (in theory) more file space to be reused more quickly.  The VALUE should point to an integer: TRUE to turn central block pool on, and FALSE to turn it off.

GDBM_COALESCEBLKS
     NOTICE: This feature is still under study.

     Set free block merging to either on or off.  The default is off, which is how previous versions of gdbm handled free blocks.  If set, this option causes adjacent free blocks to be merged.  This can become a CPU expensive process with time, though, especially if used in conjunction with GDBM_CENTFREE.  The VALUE should point to an integer: TRUE to turn free block merging on, and FALSE to turn it off.

GDBM_SETMAXMAPSIZE
     Sets maximum size of the memory mapped region.  The VALUE should point to a value of type size_t, unsigned long or unsigned.  The actual value is rounded to the nearest page boundary (the page size is obtained from sysconf(_SC_PAGESIZE)).

The return value will be -1 upon failure, or 0 upon success.  The global variable gdbm_errno will be set upon failure.

For instance, to set a database to use a cache of 10, after opening it with gdbm_open, but prior to accessing it in any way, the following code could be used:

     int value = 10;
     ret = gdbm_setopt(dbf, GDBM_CACHESIZE, &value, sizeof(int));

File Locking.
*************

With locking disabled (if gdbm_open was called with GDBM_NOLOCK), the user may want to perform their own file locking on the database file in order to prevent multiple writers operating on the same file simultaneously.

In order to support this, the gdbm_fdesc routine is provided.

 -- gdbm interface: int gdbm_fdesc (GDBM_FILE DBF)
     Returns the file descriptor of the database DBF.  This value can be used as an argument to flock, lockf or similar calls.

Test and modify a GDBM database.
********************************

The testgdbm utility allows you to view and modify an existing GDBM database or to create a new one.

When invoked without options, it tries to open a database file called junk.gdbm, located in the current working directory.  You can change this default using the -g command line option.  This option takes a single argument, specifying the file name to open, e.g.:

     $ testgdbm -g file.db

The database will be opened in read-write mode, unless the -r option is specified, in which case it will be opened only for reading.

If the database does not exist, testgdbm will create it. There is a special option -n, which instructs the utility to create a new database.  If it is used and if the database already exists, it will be deleted, so use it sparingly.

testgdbm invocation
===================

The following table summarizes all testgdbm command line options:

-b SIZE
     Set block size.

-c SIZE
     Set cache size.

-g FILE
     Operate on FILE instead of the default junk.gdbm.

-h
     Print a concise help summary.

-n
     Create the database.

-r
     Open the database in read-only mode.

-s
     Synchronize to the disk after each write.

-v
     Print program version and licensing information and exit.

testgdbm interactive mode
=========================

After successful startup, testgdbm starts a loop, in which it reads commands from the user, executes them and prints the results on the standard output.  If the standard input is attached to a console, testgdbm runs in interactive mode, which is indicated by its prompt:

     com -> _

The utility finishes when it reads the q command (see below) or it detects end-of-file on its standard input, whichever occurs first.

A testgdbm command consists of a command letter, optionally followed by one or two arguments, separated by any amount of white space.  An argument is any sequence of non-whitespace characters.  Notice, that currently there is no way to enter arguments containing white space.  This limitation will be removed in future releases.

Each command letter takes at most two formal parameters, which can be optional or mandatory.  If the number of actual arguments is less than the number of mandatory parameters, testgdbm will prompt you to supply missing arguments.  For example, the s command takes two mandatory parameters, so if you invoked it with no arguments, you would be prompted twice to supply the necessary data, as shown in example below:

     com -> s
     key -> three
     data -> 3

However, such prompting is possible only in interactive mode.  In non-interactive mode (e.g. when running a script), all arguments must be supplied with each command, otherwise testgdbm reports an error and exits immediately.

Some commands produce excessive amounts of output.  To help you follow it, testgdbm will use a pager utility to display such output.  The name of the pager utility is taken from the environment variable PAGER.  The pager is invoked only in interactive mode and only if the estimated number of output lines is greater then the number of lines on your screen.

Many of the testgdbm commands operate on database key and data values.  The utility assumes that both keys and data are ASCII strings, either nul-terminated or not.  By default, it is assumed that strings are nul-terminated.  You can change this by using z (for keys) and Z (for data) commands.

The following table summarizes all available commands:

c
     Print the number of entries in the database.

d KEY
     Delete entry with a given KEY

e FILE-NAME [truncate]
     Export the database to the flat file FILE-NAME.  See Flat files, for a description of the flat file format and its purposes.  This command will not overwrite an existing file, unless the word truncate is given as its second argument.

     See also gdbmexport.

f KEY
     Fetch and display a record with the given KEY.

i FILE-NAME [replace]
     Import data from a flat dump file FILE-NAME (see Flat files).  If the word replace is given as the second argument, any records with the same keys as the already existing ones will replace them.

l
     List the contents of the database (see pager).

n [KEY]
2 [KEY]
     Sequential access: fetch and display a next record.  If KEY is given, a record following one with this key will be fetched. Otherwise, the key supplied by the latest 1, 2 or N command will be used.

     The second form, 2 is a synonym for n without arguments.

     See also 1, below.

     See Sequential, for more information on sequential access.

q
     Close the database and quit the utility.

s KEY DATA
     Store the DATA with KEY in the database.  If KEY already exists, its data will be replaced.

1
     Fetch and display the first record in the database.  Subsequent records can be fetched using n (or 2) command (see above). See Sequential, for more information on sequential access.

< FILE [replace]
     Read entries from FILE and store them in the database.  If the word replace is given as the second argument, any existing records with matching keys will be replaced.

r
     Reorganize the database (see Reorganization).

z
     Toggle key nul-termination.  Use S to inspect the current state.  See nul-termination.

A
     Print the avail list.

B NUM
     Print the bucket number NUM.  This command uses pager (see pager).

C
     Print the current bucket.  This command uses pager (see pager).

D
     Print hash directory.  Uses pager (see pager).

F
     Print file header.

H KEY
     Compute and display the hash value for the given KEY.

K
     Print the bucket cache.  Uses pager (see pager).

S
     Print current program status.  The following example shows the information displayed:

          Database file: junk.gdbm
          Zero terminated keys: yes
          Zero terminated data: yes

V
     Print the version of gdbm.

Z
     Toggle data nul-termination.  Use S to examine the current status.

     See nul-termination.

?
     Print a concise command summary, showing each command letter with its parameters and a short description of what it does.  Optional arguments are enclosed in square brackets.

Export a database into a portable format.
*****************************************

The gdbmexport utility converts the database into a portable flat format.  Files in this format can be used to populate databases using the gdbm_import function (see gdbm_import) or the i command of testgdbm utility (see testgdbm import).  In many cases files in this format are suitable for sending over the network to populate the database on another machine. The only exception to this are databases whose records contain non-ASCII data (e.g.  C structures, integers etc.).  For such databases you will be better off by writing a specialized utility to convert them to an architecture-independent format.

If gdbmexport is linked with libgdbm version 1.8.3, it can be used to convert databases from old to new format.

The utility takes two mandatory arguments: the name of the database file to convert and the output file name, e.g.:

     $ gdbmexport junk.gdbm junk.flat

In addition two options are understood:

-h
     Display short usage summary and exit.

-v
     Display program version and licensing information, and exit.

Useful global variables.
************************

The following global variables and constants are available:

 -- Variable: gdbm_error gdbm_errno
     This variable contains error code from the last failed gdbm call.  See Error codes, for a list of available error codes and their descriptions.

     Use gdbm_strerror (see Errors) to convert it to a descriptive text.

 -- Variable: const char * gdbm_errlist[]
     This variable is an array of error descriptions, which is used by gdbm_strerror to convert error codes to human-readable text (see Errors).  You can access it directly, if you wish so.  It contains _GDBM_MAX_ERRNO + 1 elements and can be directly indexed by the error code to obtain a corresponding descriptive text.

 -- Constant: _GDBM_MIN_ERRNO
     The minimum error code used by gdbm.

 -- Constant: _GDBM_MAX_ERRNO
     The maximum error code used by gdbm.

 -- Variable: const char * gdbm_version
     A string containing the version information.

 -- Variable: int const gdbm_version_number[3]
     This variable contains the gdbm version numbers:

     Index   Meaning
     0           Major number
     1           Minor number
     2           Patchlevel number

     Additionally, the following constants are defined in the gdbm.h file:

     GDBM_VERSION_MAJOR
          Major number.

     GDBM_VERSION_MINOR
          Minor number.

     GDBM_VERSION_PATCH
          Patchlevel number.

     These can be used to verify whether the header file matches the library.

To compare two split-out version numbers, use the following function:

 -- gdbm interface: int gdbm_version_cmp (int const A[3],
     int const B[3])
     Compare two version numbers.  Return -1 if A is less than B, 1 if A is greater than B and 0 if they are equal.

     Comparison is done from left to right, so that:

          a = { 1, 8, 3 };
          b = { 1, 8, 3 };
          gdbm_version_cmp (a, b) => 0

          a = { 1, 8, 3 };
          b = { 1, 8, 2 };
          gdbm_version_cmp (a, b) => 1

          a = { 1, 8, 3 };
          b = { 1, 9. 0 };
          gdbm_version_cmp (a, b) => -1

Error codes
***********

This chapter summarizes the error codes which can be set by the functions in gdbm library.

GDBM_NO_ERROR
     No error occurred.

GDBM_MALLOC_ERROR
     Memory allocation failed.  Not enough memory.

GDBM_BLOCK_SIZE_ERROR
     This error is set by the gdbm_open function (see Open), if the value of its BLOCK_SIZE argument is incorrect.

GDBM_FILE_OPEN_ERROR
     The library was not able to open a disk file.  This can be set by gdbm_open (see Open), gdbm_export and gdbm_import functions (see Flat files).

GDBM_FILE_WRITE_ERROR
     Writing to a disk file failed.  This can be set by gdbm_open (see Open), gdbm_export and gdbm_import functions.

GDBM_FILE_SEEK_ERROR
     Positioning in a disk file failed.  This can be set by gdbm_open (see Open) function.

GDBM_FILE_READ_ERROR
     Reading from a disk file failed.  This can be set by gdbm_open (see Open), gdbm_export and gdbm_import functions.

GDBM_BAD_MAGIC_NUMBER
     The file given as argument to gdbm_open function is not a valid gdbm file: it has a wrong magic number.

GDBM_EMPTY_DATABASE
     The file given as argument to gdbm_open function is not a valid gdbm file: it has zero length.

GDBM_CANT_BE_READER
     This error code is set by the gdbm_open function if it is not able to lock file when called in GDBM_READER mode (see GDBM_READER).

GDBM_CANT_BE_WRITER
     This error code is set by the gdbm_open function if it is not able to lock file when called in writer mode (see Open).

GDBM_READER_CANT_DELETE
     Set by the gdbm_delete (see Delete) if it attempted to operate on a database that is open in read-only mode (see GDBM_READER).

GDBM_READER_CANT_STORE
     Set by the gdbm_store (see Store) if it attempted to operate on a database that is open in read-only mode (see GDBM_READER).

GDBM_READER_CANT_REORGANIZE
     Set by the gdbm_reorganize (see Reorganization) if it attempted to operate on a database that is open in read-only mode (see GDBM_READER).

GDBM_UNKNOWN_UPDATE
     Currently unused.  Reserved for future uses.

GDBM_ITEM_NOT_FOUND
     Requested item was not found.  This error is set by gdbm_delete (see Delete) and gdbm_fetch (see Fetch) when the requested KEY value is not found in the database.

GDBM_REORGANIZE_FAILED
     The gdbm_reorganize function is not able to create a temporary database.  See Reorganization.

GDBM_CANNOT_REPLACE
     Cannot replace existing item.  This error is set by the gdbm_store if the requested KEY value is found in the database and the FLAG parameter is not GDBM_REPLACE. See Store, for a detailed discussion.

GDBM_ILLEGAL_DATA
     Either KEY or CONTENT parameter was wrong in a call to to gdbm_store (see Store).

GDBM_OPT_ALREADY_SET
     Requested option can be set only once and was already set.  This error is returned by the gdbm_setopt function.  See GDBM_CACHESIZE.

GDBM_OPT_ILLEGAL
     The OPTION argument is not valid or the VALUE argument points to an invalid value in a call to gdbm_setopt function. See Options.

GDBM_BYTE_SWAPPED
     The gdbm_open function (see Open) attempts to open a database which is created on a machine with different byte ordering.

GDBM_BAD_FILE_OFFSET
     The gdbm_open function (see Open) sets this error code if the file it tries to open has a wrong magic number.

GDBM_BAD_OPEN_FLAGS
     Set by the gdbm_export function if supplied an invalid FLAGS argument.  See Flat files.

Compatibility with standard dbm and ndbm.
*****************************************

Gdbm includes a compatibility layer, which provides traditional ndbm and older dbm functions.  The layer is compiled and installed if the --enable-libgdbm-compat option is used when configuring the package.

The compatibility layer consists of two header files: ndbm.h and dbm.h and the libgdbm_compat library.

Older programs using ndbm or dbm interfaces can use libgdbm_compat without any changes.  To link a program with the compatibility library, add the following two options to the cc invocation: -lgdbm -lgdbm_compat.  The -L option may also be required, depending on where gdbm is installed, e.g.:

     cc ... -L/usr/local/lib -lgdbm -lgdbm_compat

Databases created and manipulated by the compatibility interfaces consist of two different files: FILE.dir and FILE.pag.  This is required by the POSIX specification and corresponds to the traditional usage.  Note, however, that despite the similarity of the naming convention, actual data stored in these files has not the same format as in the databases created by other dbm or ndbm libraries.  In other words, you cannot access a standard UNIX dbm file with GNU dbm!

GNU dbm files are not sparse.  You can copy them with the usual cp command and they will not expand in the copying process.

NDBM interface functions.
=========================

The functions below implement the POSIX ndbm interface:

 -- ndbm: DBM * dbm_open (char *FILE, int FLAGS, int MODE)
     Opens a database.  The FILE argument is the full name of the database file to be opened.  The function opens two files: FILE.pag and FILE.dir.  The FLAGS and MODE arguments have the same meaning as the second and third arguments of open (see open a file (open(2) man page)), except that a database opened for write-only access opens the files for read and write access and the behavior of the O_APPEND flag is unspecified.

     The function returns a pointer to the DBM structure describing the database.  This pointer is used to refer to this database in all operations described below.

 -- ndbm: void dbm_close (DBM *DBF)
     Closes the database.  The DBF argument must be a pointer returned by an earlier call to dbm_open.

 -- ndbm: datum dbm_fetch (DBM *DBF, datum KEY)
     Reads a record from the database with the matching key.  The KEY argument supplies the key that is being looked for.

     If no matching record is found, the dptr member of the returned datum is NULL.  Otherwise, the dptr member of the returned datum points to the memory managed by the compatibility library.  The application should never free it.

 -- ndbm: int dbm_store (DBM *DBF, datum KEY,
     datum CONTENT, int MODE)
     Writes a key/value pair to the database.  The argument DBF is a pointer to the DBM structure returned from a call to dbm_open.  The KEY and CONTENT provide the values for the record key and content.  The MODE argument controls the behavior of dbm_store in case a matching record already exists in the database.  It can have one of the following two values:

     DBM_REPLACE
          Replace existing record with the new one.

     DBM_INSERT
          The existing record is left unchanged, and the function returns 1.

     If no matching record exists in the database, new record will be inserted no matter what the value of the MODE is.

 -- ndbm: int dbm_delete (DBM *DBF, datum KEY)
     Deletes the record with the matching key from the database.  If the function succeeds, 0 is returned.  Otherwise, if no matching record is found or if an error occurs, -1 is returned.

 -- ndbm: datum dbm_firstkey (DBM *DBF)
     Initializes iteration over the keys from the database and returns the first key.  Note, that the word first does not imply any specific ordering of the keys.

     If there are no records in the database, the dptr member of the returned datum is NULL.  Otherwise, the dptr member of the returned datum points to the memory managed by the compatibility library.  The application should never free it.

 -- ndbm: datum dbm_nextkey (DBM *DBF)
     Continues the iteration started by dbm_firstkey.  Returns the next key in the database.  If the iteration covered all keys in the database, the dptr member of the returned datum is NULL. Otherwise, the dptr member of the returned datum points to the memory managed by the compatibility library.  The application should never free it.

     The usual way of iterating over all the records in the database is:

          for (key = dbm_firstkey (dbf);
               key.ptr;
               key = dbm_nextkey (dbf))
            {
              /* do something with the key */
            }

     The loop above should not try to delete any records from the database, otherwise the iteration is not guaranteed to cover all the keys. See Sequential, for a detailed discussion of this.

 -- ndbm: int dbm_error (DBM *DBF)
     Returns the error condition of the database: 0 if no errors occurred so far while manipulating the database, and a non-zero value otherwise.

 -- ndbm: void dbm_clearerr (DBM *DBF)
     Clears the error condition of the database.

 -- ndbm: int dbm_dirfno (DBM *DBF)
     Returns the file descriptor of the dir file of the database. It is guaranteed to be different from the descriptor returned by the dbm_pagfno function (see below).

     The application can lock this descriptor to serialize accesses to the database.

 -- ndbm: int dbm_pagfno (DBM *DBF)
     Returns the file descriptor of the pag file of the database. See also dbm_dirfno.

 -- ndbm: int dbm_rdonly (DBM *DBF)
     Returns 1 if the database DBF is open in a read-only mode and 0 otherwise.

DBM interface functions.
========================

The functions below are provided for compatibility with the old UNIX DBM interface.  Only one database at a time can be manipulated using them.

 -- dbm: int dbminit (char *FILE)
     Opens a database.  The FILE argument is the full name of the database file to be opened.  The function opens two files: FILE.pag and FILE.dir.  If any of them does not exist, the function fails.  It never attempts to create the files.

     The database is opened in the read-write mode, if its disk permissions permit.

     The application must ensure that the functions described below in this section are called only after a successful call to dbminit.

 -- dbm: int dbmclose (void)
     Closes the database opened by an earlier call to dbminit.

 -- dbm: datum fetch (datum KEY)
     Reads a record from the database with the matching key.  The KEY argument supplies the key that is being looked for.

     If no matching record is found, the dptr member of the returned datum is NULL.  Otherwise, the dptr member of the returned datum points to the memory managed by the compatibility library.  The application should never free it.

 -- dbm: int store (datum KEY, datum CONTENT)
     Stores the key/value pair in the database.  If a record with the matching key already exists, its content will be replaced with the new one.

     Returns 0 on success and -1 on error.

 -- dbm: int delete (datum KEY)
     Deletes a record with the matching key.

     If the function succeeds, 0 is returned.  Otherwise, if no matching record is found or if an error occurs, -1 is returned.

 -- dbm: datum firstkey (void)
     Initializes iteration over the keys from the database and returns the first key.  Note, that the word first does not imply any specific ordering of the keys.

     If there are no records in the database, the dptr member of the returned datum is NULL.  Otherwise, the dptr member of the returned datum points to the memory managed by the compatibility library.  The application should never free it.

 -- dbm: datum nextkey (datum KEY)
     Continues the iteration started by a call to firstkey.  Returns the next key in the database.  If the iteration covered all keys in the database, the dptr member of the returned datum is NULL. Otherwise, the dptr member of the returned datum points to the memory managed by the compatibility library.  The application should never free it.

Problems and bugs.
******************

If you have problems with GNU dbm or think you've found a bug, please report it.  Before reporting a bug, make sure you've actually found a real bug.  Carefully reread the documentation and see if it really says you can do what you're trying to do.  If it's not clear whether you should be able to do something or not, report that too; it's a bug in the documentation!

Before reporting a bug or trying to fix it yourself, try to isolate it to the smallest possible input file that reproduces the problem.  Then send us the input file and the exact results gdbm gave you.  Also say what you expected to occur; this will help us decide whether the problem was really in the documentation.

Once you've got a precise problem, send e-mail to bug-gdbm@gnu.org.

Please include the version number of GNU dbm you are using.  You can get this information by printing the variable gdbm_version (see Variables).

Non-bug suggestions are always welcome as well.  If you have questions about things that are unclear in the documentation or are just obscure features, please report them too.

You may contact the authors and maintainers by e-mail:

     phil@cs.wwu.edu, downsj@downsj.com, gray@gnu.org.ua

Additional resources
********************

For the latest updates and pointers to additional resources, visit http://www.gnu.org/software/gdbm.

In particular, a copy of gdbm documentation in various formats is available online at http://www.gnu.org/software/gdbm/manual.

Latest versions of gdbm can be downloaded from anonymous FTP: ftp://ftp.gnu.org/gnu/gdbm, or via HTTP from http://ftp.gnu.org/gnu/gdbm, or from any GNU mirror worldwide.  See http://www.gnu.org/order/ftp.html, for a list of mirrors.

To track gdbm development, visit http://puszcza.gnu.org.ua/projects/gdbm.

GNU Free Documentation License
******************************

     [file fdl.texi not included]