C++ 实现字符串值的cdbpp库

C++ 实现字符串值的cdbpp库,c++,fstream,C++,Fstream,我正在尝试从chokkan实现cdbpp库。当我试图为数据类型为字符串的值实现相同的值时,我遇到了一些问题 原始代码和文档可在此处找到: git源代码如下: 这就是我到目前为止所做的: 在sample.cpp(从这里调用main函数)中,我修改了build()函数: bool build() { // Open a database file for writing (with binary mode). std::ofstream ofs(DBNAME, std::ios_base::bina

我正在尝试从chokkan实现cdbpp库。当我试图为数据类型为
字符串的值实现相同的值时,我遇到了一些问题

原始代码和文档可在此处找到: git源代码如下:

这就是我到目前为止所做的: 在sample.cpp(从这里调用main函数)中,我修改了
build()
函数:

bool build()
{
// Open a database file for writing (with binary mode).
std::ofstream ofs(DBNAME, std::ios_base::binary);
if (ofs.fail()) {
    std::cerr << "ERROR: Failed to open a database file." << std::endl;
    return false;
}

try {
    // Create an instance of CDB++ writer.
    cdbpp::builder dbw(ofs);

    // Insert key/value pairs to the CDB++ writer.
    for (int i = 1;i < N;++i) {
        std::string key = int2str(i);
        const char* val = "foobar";  //string value here
        dbw.put(key.c_str(), key.length(), &val, sizeof(i));
    }


} catch (const cdbpp::builder_exception& e) {
    // Abort if something went wrong...
    std::cerr << "ERROR: " << e.what() << std::endl;
    return false;
}

return true;
}
现在,如果字符串小于或等于3个字符,我将获得正确的值(例如:foo将返回foo)。如果它大于3,它将为我提供最多3个字符的正确字符串,然后垃圾值(例如,foobar为我提供foo�`)

<>我对C++有点新,我会很感激你给我的任何帮助。

< P>(移动评论中的可能答案到真实答案)


传递到put中的vsize是一个整数的大小,当它应该是值字符串的长度时。

什么类型是键?一般来说,您不能二进制转储类并期望它工作。确保vsize不大于字符串大小。
vsize
传递到
put
是一个整数的大小,当它应该是值字符串的长度时
字符串。是的,解决了它。我不知道我怎么会错过它。
void put(const key_t *key, size_t ksize, const value_t *value, size_t vsize)
{
    // Write out the current record.
    std::string temp2 = *value;
    const char* temp = temp2.c_str();
    write_uint32((uint32_t)ksize);
    m_os.write(reinterpret_cast<const char *>(key), ksize);
    write_uint32((uint32_t)vsize);
    m_os.write(reinterpret_cast<const char *>(temp), vsize);
    // Compute the hash value and choose a hash table.
    uint32_t hv = hash_function()(static_cast<const void *>(key), ksize);
    hashtable& ht = m_ht[hv % NUM_TABLES];

    // Store the hash value and offset to the hash table.
    ht.push_back(bucket(hv, m_cur));

    // Increment the current position.
    m_cur += sizeof(uint32_t) + ksize + sizeof(uint32_t) + vsize;

}