我正在尝试从 chokkan 实现 cdbpp 库。当我尝试对数据类型为 strings
的值实现相同的操作时,我遇到了一些问题。
原始代码和文档可以在这里找到: http://www.chokkan.org/software/cdbpp/ git 源代码在这里:https://github.com/chokkan/cdbpp
这是我目前所拥有的:
在 sample.cpp(从我调用主函数的地方)中,我修改了 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;
}
在 cdbpp.h 文件中,我将 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;
}
现在,如果字符串小于或等于 3 个字符,我将得到正确的值(例如:foo 将返回 foo)。如果它大于 3,它会给我最多 3 个字符的正确字符串,然后是垃圾值(例如 foobar 给我 foo`)
我对 C++ 有点陌生,如果你能给我任何帮助,我将不胜感激。
最佳答案
(将评论中的可能答案移动到真实答案)
传递给 put 的 vsize 是一个整数的大小,而它应该是值字符串的长度。
关于c++ - 为字符串值实现 cdbpp 库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33951053/