DBM is a lightweight data storage library in Linux. It is not a database, because it can only save the most basic key-> value, but is only an indexed file storage system.
Its storage efficiency is average, and the query efficiency is good. The second-level flash sales of million is enough for simple applications, So you no longer need to find something to save. This can be done simply ~
Reference: http://dev.csdn.net/article/67/67908.shtm this article is to sort out the Linux programming related chapter, I also learned through this book, the function and design ideas are very simple, at a glance will be
Paste and save the data code:
# Include <unistd. h>
# Include <stdlib. h>
# Include <stdio. h>
# Include <fcntl. h>
# Include <gdbm-ndbm.h>
# Include <string. h>
# Define items_count 1000000
Typedef struct
{
Int num;
Int value;
} Test_data;
Int set_test_data (test_data * DT, int N, int value)
{
If (! DT)
{
Return-1;
}
DT-> num = N;
DT-> value = value;
Return 0;
}
Int main ()
{
DBM * db_file;
Test_data items [items_count];
Test_data record;
Char key [20];
Int I;
Datum key_datum;
Datum data_datum;
Int result;
Memset (Key, 0, sizeof (key ));
Db_file = dbm_open ("test_db", o_rdwr | o_creat, 0666 );
Memset (items, 0, sizeof (items ));
For (I = 0; I <items_count; I ++)
{
Items [I]. num = I;
Items [I]. value = I + 50;
}
For (I = 0; I <items_count; I ++)
{
Sprintf (key, "% d", items [I]. Num, items [I]. value );
// Printf ("% s \ r \ n", key );
Key_datum.dptr = (void *) Key;
Key_datum.dsize = strlen (key );
Data_datum.dptr = (void *) & items [I];
Data_datum.dsize = sizeof (test_data );
Result = dbm_store (db_file, key_datum, data_datum, dbm_replace );
If (result! = 0)
{
Fprintf (stderr, "dbm_store failed on key: % s \ n", key );
Exit (exit_failure );
}
}
Dbm_close (db_file );
Exit (exit_success );
}
Query code:
# Include <unistd. h>
# Include <stdlib. h>
# Include <stdio. h>
# Include <fcntl. h>
# Include <gdbm-ndbm.h>
# Include <string. h>
Typedef struct
{
Int num;
Int value;
} Test_data;
Int main ()
{
DBM * db_file;
Char key [20];
Datum key_datum;
Datum data_datum;
Test_data record;
Db_file = dbm_open ("test_db", o_rdwr | o_creat, 0666 );
Memset (Key, 0, 20 );
If (! Db_file)
{
Fprintf (stderr, "Open Database Error ");
Exit (exit_failure );
}
Sprintf (key, "% d", 500000,500050 );
Key_datum.dptr = (void *) Key;
Key_datum.dsize = strlen (key );
Data_datum = dbm_fetch (db_file, key_datum );
If (! Data_datum.dptr)
{
Fprintf (stderr, "Fetch data error \ n ");
Exit (exit_failure );
}
Memcpy (& record, data_datum.dptr, data_datum.dsize );
Printf ("% d-% d \ r \ n", record. Num, record. value );
Dbm_close (db_file );
Exit (exit_success );
}
The example is not very good. During the test, the number is changed from above. Pay attention to the uniqueness of the index.