Berkeley DB C++ 显示不正确的键值字符串数据

Berkeley DB C++ showing incorrect key-value string data

我已经用 VCPKG 安装了 Berkeley DB。

我正在尝试使用 Berkeley DB 存储简单的键值对。喜欢

fruit = apple

#include <sys/types.h>
#include <stdio.h>
#include <db.h>
#include <stdlib.h>
#include <vcruntime_string.h>
#include <iostream>

#define DATABASE "access.db"

using namespace std;

int main()
{
    DB* dbp;
    DBT key, data;
    int ret;
    if ((ret = db_create(&dbp, NULL, 0)) != 0)
    {
        fprintf(stderr, "db_create: %s\n", db_strerror(ret));
        cout << "db_create :" << db_strerror(ret) << endl;
    }
    else
        cout << "db_created or exists" << endl;

    if ((ret = dbp->open(dbp,
        NULL, DATABASE, NULL, DB_BTREE, DB_CREATE, 0664)) != 0) {
        dbp->err(dbp, ret, "%s", DATABASE);
        cout << "can not open db" << DATABASE << endl;
    }
    else {
        cout << "opened " << DATABASE << endl;
    }
    const char* fruit = "fruit";
    const char* apple = "apple";
    memset(&key, 0, sizeof(key));
    memset(&data, 0, sizeof(data));
    key.data = &fruit;
    key.size = sizeof(fruit);
    data.data = &apple;
    data.size = sizeof(apple);

    if ((ret = dbp->put(dbp, NULL, &key, &data, 0)) == 0)
        cout << "db: key stored :" << (const char*)key.data << endl;
    else
        dbp->err(dbp, ret, "DB->put");

    DBT key1, value1;
    memset(&key1, 0, sizeof(key1));
    memset(&value1, 0, sizeof(value1));
    key1.data = &fruit;
    key1.size = sizeof(fruit);

    if ((ret = dbp->get(dbp, NULL, &key1, &value1, 0)) == 0)
        cout << "db: value fetched :" << (const char*)value1.data << endl;
    else
        dbp->err(dbp, ret, "DB->get");

    return 0;
}

DBT 数据库事务实例需要一个空指针 void * 作为输入,所以我传递了引用。该代码有效,但是当我从 DBT 转换数据值时,它显示 junk/illegible 个字符。我不知道问题是什么

输出

db: key stored :£┴₧÷
db: value fetched :ñ┴₧÷

我尝试过的事情:

db: key stored :000000C6B78FFC68
db: value fetched :0000025996F56C70
db: key stored :£┴┘à÷
db: value fetched :ñ┴┘à÷
db: key stored :£┴₧÷
db: value fetched :ñ┴₧÷
db: key stored :£
db: value fetched :ñ

如何从 Berkeley DB 获取可读文本?我在存储数据本身时做错了什么吗?

我是 C++ 的初学者,所以我不知道还能做什么。

const char* fruit = "fruit";

这意味着 sizeof(fruit) 是您平台上 const char * 的大小。这也意味着 &fruit 是这个特定指针在您的平台上的存储位置。鉴于这两件事:

data.data = &apple;
data.size = sizeof(apple);

这两行都没有任何意义。您应该将指针指向 data 中的数据,而不是指向 const char * 的指针。您应该将数据的大小放在 size 中,而不是 const char *.

的大小

尝试:

data.data = (void *) apple;
data.size = strlen(apple);

解决方案是将键值的数据类型从常量字符指针 const char * 更改为字符数组。

char fruit[sizeof("fruit")] = "fruit";
char apple[sizeof("apple")] = "apple";

此外,即使使用 string 而不是 const char * 作为键值也会产生与问题中提到的类似的问题,不知何故我可以让它只适用于 char 数组。 参考:BerkeleyDB.example