如何使用C++在注册表中插入变量值

How to insert variables values in the registry with C++?

本文关键字:插入 变量值 注册表 何使用 C++      更新时间:2023-10-16

可能重复:
字符数组初始化时出错

我想在windows注册表中插入一个环境变量,所以我绑定了以下C++代码:

string appDataPath = getenv("appdata");
    HKEY hkey;
    char value[] = appDataPath.c_str();
    RegOpenKeyEx(HKEY_CURRENT_USER, "Software\Microsoft\Windows\Currentversion\Run", 0, KEY_SET_VALUE, &hkey);
    RegSetValueEx (hkey, "MyProgram", 0, REG_SZ, (LPBYTE) value, strlen(value) + 1);
    RegCloseKey(hkey);

代码块调试输出告诉我:error: initializer fails to determine size of 'value'我认为这是因为编译器在编译之前需要知道我的变量的大小,但我不知道如何解决这个问题。。。

谢谢!

c_str()返回const char*,而不是char[]。更改

char value[] = appDataPath.c_str();

const char* value = appDataPath.c_str();

编译器给出错误是因为数组变量需要一个长度,但没有提供。

使用

const char * value = appDataPath.c_str();

(读取<string>引用以查找c_str()的返回类型,它会告诉您它确实是const char *。(


关于如何连接两个字符串的问题:

使用C++字符串而不是char *执行此操作,并稍后转换它们:

string newstring = appDataPath;
newstring.append("some text");
const char * value = newstring.c_str();