Next: , Previous: , Up: Top   [Contents][Index]


7 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, inspect the value of the gdbm_errno variable (see gdbm_errno). If it is GDBM_ITEM_NOT_FOUND, no data was found. Any other value means an error occurred. Use gdbm_strerror function to convert gdbm_errno to a human-readable string.

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)
  {
    if (gdbm_errno == GDBM_ITEM_NOT_FOUND)
      fprintf(stderr, "key not found\n");
    else
      fprintf(stderr, "error: %s\n", gdbm_db_strerror (dbf));
  }
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)

Checks whether the key exists in the database dbf.

If key is found, returns true (1). If it is not found, returns false (0) and sets gdbm_errno to GDBM_NO_ERROR (0).

On error, returns 0 and sets gdbm_errno to a non-0 error code.

The parameters are:

dbf

The pointer returned by gdbm_open.

key

The search key.