把玩了一下gdbm
它的存储效率一般,查询效率还不错,100W级别秒杀的,简单应用够了,这下再也不用到处找东西保存了,简单的这个就能搞定了,呵呵~
参考资料:http://dev.csdn.net/article/67/67908.shtm 这篇文章是整理的LINUX程序设计相关章节,我也是通过这本书来学习的,函数和设计思想都很简单,一看就会了
先贴保存数据代码:
#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%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);
}
查询的代码:
#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%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);
}
例子不是很好,测试的时候,是从上面改数的,注意索引的唯一性