我正在尝试用C学习gnu gdbm编程,但是由于gdbm教程、书籍等的不足,我无法继续学习,所以我必须遵循的唯一事情是w3上可用的几个简单的gdbm代码。我在两个独立的.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;
}发布于 2012-09-12 18:12:36
包括尾随“\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“。
https://stackoverflow.com/questions/12393680
复制相似问题