我正在尝试使用C学习gnu gdbm编程,但由于缺少gdbm教程,书籍等而无法继续编程。所以我唯一需要遵循的是w3上可用的几个简单的gdbm c api代码。我在两个单独的.c文件的帮助下编写并编译了以下代码,但它无法从数据库“testdb”获取数据,所以请告诉我哪里出错了。首先它 存储一个字符串,在第二部分中,它获取数据。输出是; 找不到钥匙。
#include <stdio.h>
#include <gdbm.h>
#include <stdlib.h>
#include <string.h>
int
main(void)
{
GDBM_FILE dbf;
datum key = { "testkey", 7 }; /* key, length */
datum value = { "testvalue", 9 }; /* value, length */
printf ("Storing key-value pair... \n");
dbf = gdbm_open("testdb", 0, GDBM_NEWDB,0666, 0);
gdbm_store (dbf, key, value, GDBM_INSERT);
printf ("key: %s size: %d\n", key.dptr, key.dsize);
gdbm_close (dbf);
printf ("done.\n\n");
dbf = gdbm_open("testdb", 0, GDBM_READER, 0666, 0);
if (!dbf)
{
fprintf (stderr, "File %s either doesn't exist or is not a gdbm file.\n", "testdb");
exit (1);
}
key.dsize = strlen("testkey") + 1;
value = gdbm_fetch(dbf, key);
if (value.dsize > 0) {
printf ("%s\n", value.dptr);
free (value.dptr);
}
else {
printf ("Key %s not found.\n", key.dptr);
}
gdbm_close (dbf);
return 0;
}
答案 0 :(得分:1)
包括尾随'\ 0'的长度。
datum key = { "testkey", 8 }; /* key, length */
datum value = { "testvalue", 10 }; /* value, length */
- 编辑:
关于您评论的链接:http://www-rohan.sdsu.edu/doc/gdbm/example.html
仔细阅读第一个要点:“我假设编写密钥和数据的过程包括终止空字符....”
因此;的或者强>:
datum key = { "testkey", 8 }; /* Include \0 in length */
datum value = { "testvalue", 10 };
和
key.dsize = strlen("testkey") + 1; /* +1 for the trailing \0 */
或强>
datum key = { "testkey", 7 }; /* Skip \0 in length */
datum value = { "testvalue", 9 };
和
key.dsize = strlen("testkey"); /* Do not +1 */
首先版本通常是首选的,因为非空终止的c字符串可能很难处理。
希望它有所帮助。
- 编辑2(对不起,继续考虑新事物):
另请注意,如果你说即:。
datum value = { "testvalue", 5 }; /* value, length */
存储的值为“testv”。