如何将REG_MULTI_SZ值写入注册表
How do I write REG_MULTI_SZ values to the Registry?
我正在尝试使用c++编写REG_MULTI_SZ值到Windows注册表。我卡住的地方是在转换我必须MULTI_SZ格式的c字符串。有什么方便的方法吗?
你得自己做。鉴于
char ** strings; // array of strings
int N; // number of strings
计算multi_sz
的长度int len=1;
for(int i=0; i<N; i++)
len += strlen(strings[i])+1;
并填充
char* multi_sz = malloc(len), ptr=multi_sz;
memset(multi_sz, 0, len);
for(int i=0; i<N; i++) {
strcpy(ptr, strings[i]);
ptr += strlen(strings[i])+1;
}
这是一个c++ 0x的替代方案。
static const std::string vals [] =
{
"a", "bb", "ccc"
};
static const size_t num_vals = sizeof(vals)/sizeof(vals[0]);
std::string reg_out = std::accumulate(&vals[0], &vals[num_vals], std::string(), [](std::string& so_far, const std::string& cur) -> std::string
{
so_far += cur;
so_far += ' ';
return so_far;
});
reg_out += ' ';
reg_out.size();
RegSetValueEx(...,...,...,REG_MULTI_SZ, rerinterpret_cast<const BYTE*>(®_out[0]), reg_out.size());
如果所有值都是常量,那么您可能需要使用字符串字面值,而不是不必要地组合字符串。
如果你用字符串字面值构造一个c++字符串,那么第一个空字符将终止它:
string s("aaa bbb"); // constructs the string "aaa"
但是,c++字符串可以包含空字符,并且可以从包含空字符的字符串字面量构造,如下所示:
const char sz[] = "aaa bbb";
string szs(sz, sizeof(sz) / sizeof(char)); // constructs the string "aaa bbb"
然后你可以简单地做:
RegSetValueEx(...,...,...,REG_MULTI_SZ, rerinterpret_cast<const BYTE*>(&szs[0]), szs.size());
请注意,与其他答案中建议的不同,不需要在值的末尾使用两个空字符(一个用于终止最后一个字符串,另一个用于终止列表)。这样做实际上会将一个空字符串添加到值列表中,这可能是不希望的。在本例中,第二个字符串(以及整个列表)以null字符结束,该字符被自动添加到c++字符串的末尾。
相关文章:
- 有没有任务栏API可以立即应用注册表更改
- 检查注册表项是否链接到(或副本)另一个注册表项
- 禁用地址共享注册表不起作用
- 如何从注册表项中提取配置单元和注册表名称
- 注册表正在设置 1 个字符
- 清理"QSettings"注册表项的最佳方法(Windows上的Qt 5)
- 在 c++ 中编辑注册表项
- 某些进程的注册表限制
- 在编译时生成某种子类/类型注册表?
- 如何测试注册表项是否存在?
- 注册表-获取值(而不是键)上次更改的时间和键创建日期
- 从注册表中检索已注销用户的 sid
- 如何正确检查 c++ 是否存在注册表项?
- 如何在不使用任何数据库的情况下制作动态注册表单?
- 强制资源管理器重新加载注册表值
- 以编程方式锁定注册表项以避免并发问题
- 如何应用注册表模式使"select class depend on input"遵守开放封闭原则?
- 如何恢复注册表项的有效权限?C++
- 如何防止 C API 注册表中的 Lua 回调被垃圾回收?
- 如何修改QT中的注册表设置