Linux dBm Database

Source: Internet
Author: User

Gdbm is installed by default in most mainstream Linux distributions, but in some distributions, you may need to use the Package Manager to install the corresponding development library. For example

In ubuntu, you may need to use the Synaptic Package Manager to install the libgdbm-dev package, because it is generally not installed by default.

DBM data block datum is a type defined by typedef statements. It contains at least two members:

Void * dptr;

Size_t dsize;

DBM access functions include the following four:

#include<ndbm.h>DBM *dbm_open(const char *filename, int file_open_flags , mode_t mode);int dbm_store(DBM *database_descriptor , datum key, datum content, int store_mode);datum datum_fetch(DBM *database_descriptor , datum key);void dbm_close(DBM *database_descriptor);

1. dbm_open Function

This function can be used to open an existing database or create a new database. The filename parameter is a basic file name that does not contain the. DIR or. PAG suffix.

The remaining parameters are the same as the second and third parameters of the open function.

Dbm_open returns a pointer to the DBM type. It is used for all subsequent accesses to the database. If it fails, it returns (DBM *) 0.

2. dbm_store Function

You use this function to store data in the database. As mentioned above, all data must have a unique index.

To define the data you want to store and the indexes used to apply the data, you must set two datum-type parameters: one for referencing the index and the other for actual use.

Data. The last store_mode parameter is used to control the situation when an existing keyword is used to store data. If it is set to dbm_insert

The storage operation fails and dbm_store returns 1. If it is set to dbm_replace, the new data will overwrite the existing data and dbm_store returns 0.

If other errors occur, dbm_store returns a negative value.

3. dbm_fetch Function

The dbm_fetch function is used to retrieve data from the database. It uses a pointer returned by the previous dbm_open call and a datum type structure pointing to the keyword as the parameter.

It returns a structure of the datum type. If the data associated with this keyword is found in the database, but the dptr and dsize members of the datum Structure

The value is set as the value of the corresponding data. If no keyword is found, dptr is set to null;

4. dbm_close Function

This function is used to close the database opened by the dbm_open function. Its parameter is the DBM pointer returned by the previous dbm_open call.

# Include <unistd. h> # include <stdlib. h> # include <stdio. h> # include <fcntl. h> # include <ndbm. h>/* On some systems you need to replace the above with # include <gdbm-ndbm.h> */# include <string. h> # define test_db_file "/tmp/dbm1_test" # define items_used 3/* a struct to use to test dBm */struct test_data {char misc_chars [15]; int any_integer; char more_chars [21] ;}; int main () {struct test_data items_to_store [Items_used]; struct test_data partition; char key_to_use [20]; int I, result; datum key_datum; datum data_datum; dBm * dbm_ptr; dbm_ptr = dbm_open (test_db_file, credential | o_creat, 0666); If (! Dbm_ptr) {fprintf (stderr, "failed to open database \ n"); exit (exit_failure);}/* put some data in the structures */memset (items_to_store, '\ 0', sizeof (items_to_store); strcpy (items_to_store [0]. misc_chars, "first! "); Items_to_store [0]. any_integer = 47; strcpy (items_to_store [0]. more_chars, "foo"); strcpy (items_to_store [1]. misc_chars, "bar"); items_to_store [1]. any_integer = 13; strcpy (items_to_store [1]. more_chars, "unlucky? "); Strcpy (items_to_store [2]. misc_chars, "third"); items_to_store [2]. any_integer = 3; strcpy (items_to_store [2]. more_chars, "Baz"); for (I = 0; I <items_used; I ++) {/* build a key to use */sprintf (key_to_use, "% C % d", items_to_store [I]. misc_chars [0], items_to_store [I]. more_chars [0], items_to_store [I]. any_integer);/* build the key datum strcture */key_datum.dptr = (void *) key_to_use; key_datum. Dsize = strlen (key_to_use); region = (void *) & items_to_store [I]; region = sizeof (struct test_data); Result = dbm_store (dbm_ptr, key_datum, data_datum, dbm_replace ); if (result! = 0) {fprintf (stderr, "dbm_store failed on key % s \ n", key_to_use); exit (2 );}} /* For * // * now try and retrieve some data */sprintf (key_to_use, "Bu % d", 13 ); /* This is the key for the second item */keys = key_to_use;/* test */key_datum.dsize = strlen (key_to_use); data_datum = dbm_fetch (dbm_ptr, key_datum ); if (data_datum.dptr) {printf ("data retrieved \ n"); memcpy (& item_retrieved, data_datum.dptr, data_datum.dsize ); printf ("retrieved item-% S % d % s \ n", item_retrieved.misc_chars, item_retrieved.any_integer, expiration);} else {printf ("no data found for key % s \ n ", key_to_use);} dbm_close (dbm_ptr); exit (exit_success );}

Other dBm Functions

Int dbm_delete (DBM * database_descriptor, datum key );

This function is used to delete data items from the database. Like dbm_fetch, it also uses a datum type structure pointing to the keyword as its parameter, but the difference is that it is used

Delete data instead of used to retrieve data. It returns 0 if successful.

Int dbm_error (DBM * database_descriptor );

The function is used to test whether an error occurs in the database. If no error occurs, 0 is returned.

Int dbm_clearerr (DBM * database_descriptor );

The function is used to clear all error condition signs that have been set in the database.

Datum dbm_firstkey (DBM * database_descriptor );

Datum dbm_nextkey (DBM * database_descriptor );

These two functions are usually paired to scan all keywords in the database. The loop structure they need is as follows:

DBM * db_ptr;

Datum key;

For (Key = dbm_firstkey (db_ptr); key. dptr; Key = dbm_nextkey (db_ptr ));

#include <unistd.h>#include <stdlib.h>#include <stdio.h>#include <fcntl.h>#include <ndbm.h>/* On some systems you need to replace the above with#include <gdbm-ndbm.h>*/#include <string.h>#define TEST_DB_FILE "/tmp/dbm2_test"#define ITEMS_USED 3/* A struct to use to test dbm */struct test_data {    char misc_chars[15];    int  any_integer;    char more_chars[21];};int main() {    struct test_data items_to_store[ITEMS_USED];    struct test_data item_retrieved;    char key_to_use[20];    int i, result;    datum key_datum;    datum data_datum;        DBM *dbm_ptr;    dbm_ptr = dbm_open(TEST_DB_FILE, O_RDWR | O_CREAT, 0666);    if (!dbm_ptr) {        fprintf(stderr, "Failed to open database\n");        exit(EXIT_FAILURE);            }        /* put some data in the structures */    memset(items_to_store, '\0', sizeof(items_to_store));    strcpy(items_to_store[0].misc_chars, "First!");    items_to_store[0].any_integer = 47;    strcpy(items_to_store[0].more_chars, "foo");    strcpy(items_to_store[1].misc_chars, "bar");    items_to_store[1].any_integer = 13;    strcpy(items_to_store[1].more_chars, "unlucky?");    strcpy(items_to_store[2].misc_chars, "Third");    items_to_store[2].any_integer = 3;    strcpy(items_to_store[2].more_chars, "baz");    for (i = 0; i < ITEMS_USED; i++) {            /* build a key to use */        sprintf(key_to_use, "%c%c%d",            items_to_store[i].misc_chars[0],            items_to_store[i].more_chars[0],            items_to_store[i].any_integer);            /* build the key datum strcture */        key_datum.dptr = key_to_use;        key_datum.dsize = strlen(key_to_use);        data_datum.dptr = (void *)&items_to_store[i];        data_datum.dsize = sizeof(struct test_data);        result = dbm_store(dbm_ptr, key_datum, data_datum, DBM_REPLACE);        if (result != 0) {            fprintf(stderr, "dbm_store failed on key %s\n", key_to_use);            exit(2);        }    } /* for */        /* now try and delete some data */    sprintf(key_to_use, "bu%d", 13); /* this is the key for the second item */    key_datum.dptr = key_to_use;    key_datum.dsize = strlen(key_to_use);    if (dbm_delete(dbm_ptr, key_datum) == 0) {        printf("Data with key %s deleted\n", key_to_use);    }    else {        printf("Nothing deleted for key %s\n", key_to_use);    }    for (key_datum = dbm_firstkey(dbm_ptr);              key_datum.dptr;              key_datum = dbm_nextkey(dbm_ptr)) {        data_datum = dbm_fetch(dbm_ptr, key_datum);        if (data_datum.dptr) {            printf("Data retrieved\n");            memcpy(&item_retrieved, data_datum.dptr, data_datum.dsize);            printf("Retrieved item - %s %d %s\n",                   item_retrieved.misc_chars,                   item_retrieved.any_integer,                   item_retrieved.more_chars);        }        else {            printf("Woops - no data found for key %s\n", key_to_use);        }    } /* for each key */        dbm_close(dbm_ptr);    exit(EXIT_SUCCESS);}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.