根据RegSetValueExA() documentation,该函数不接受std::filesystem::path 对象。这就是错误消息所抱怨的内容。
LSTATUS RegSetValueExA(
HKEY hKey,
LPCSTR lpValueName,
DWORD Reserved,
DWORD dwType,
const BYTE *lpData, // <-- here
DWORD cbData
);
第 5 个参数采用 const BYTE* 指向 以空结尾的 C 样式字符串的指针。第6个参数取字符串中的字符数,包括空终止符:
lpData
要存储的数据。
对于基于字符串的类型,例如 REG_SZ,字符串必须以 null 结尾。对于 REG_MULTI_SZ 数据类型,字符串必须以两个空字符结束。
注意lpData表示空值是有效的,但是,如果是这种情况,cbData必须设置为'0'。
cbData
lpData 参数指向的信息的大小,以字节为单位。 如果数据的类型为 REG_SZ、REG_EXPAND_SZ 或 REG_MULTI_SZ,cbData 必须包含终止空字符的大小。
std::filesystem::path 没有到const BYTE* 的隐式 转换,因此会出现编译器错误。您需要先显式将path 转换为std::string 或std::wstring(首选后者,因为注册表在内部将字符串存储为Unicode),然后才能将该字符串值保存到注册表,例如:
// using std::string...
HKEY newValue;
// don't use RegOpenKey()! It is provided only for backwards compatibility with 16bit apps...
if (RegOpenKeyExA(HKEY_CURRENT_USER, "Software\\Microsoft\\Windows\\CurrentVersion\\Run", 0, KEY_SET_VALUE, &newValue) == 0)
{
// this may lose data for non-ASCII characters!
std::string s = fs::temp_directory_path().append(filename).string();
// this will convert the ANSI string to Unicode for you...
RegSetValueExA(newValue, "myprogram", 0, REG_SZ, reinterpret_cast<LPCBYTE>(s.c_str()), s.size()+1);
RegCloseKey(newValue);
}
return 0;
// using std::wstring...
HKEY newValue;
// don't use RegOpenKey()! It is provided only for backwards compatibility with 16bit apps...
if (RegOpenKeyExW(HKEY_CURRENT_USER, L"Software\\Microsoft\\Windows\\CurrentVersion\\Run", 0, KEY_SET_VALUE, &newValue) == 0)
{
// no data loss here!
std::wstring s = fs::temp_directory_path().append(filename).wstring();
// no ANSI->Unicode conversion is performed here...
RegSetValueExW(newValue, L"myprogram", 0, REG_SZ, reinterpret_cast<LPCBYTE>(s.c_str()), (s.size()+1) * sizeof(WCHAR));
RegCloseKey(newValue);
}
return 0;