如何在C ++的Windows注册表中编写/读取字符串?
我可以使用以下代码在Windows注册表中编写/读取DWORD(数字)。但是,无法写入/读取字符串值,因为它在注册表中以字符形式存储为中文字符。
void SetVal(HKEY hKey, LPCTSTR lpValue, DWORD data)
{
LONG nError = RegSetValueEx(hKey, lpValue, NULL, REG_DWORD, (LPBYTE)&data, sizeof(DWORD));
if (nError)
cout << "Error: " << nError << " Could not set registry value: " << (char*)lpValue << endl;
}
DWORD GetVal(HKEY hKey, LPCTSTR lpValue)
{
DWORD data; DWORD size = sizeof(data); DWORD type = REG_DWORD;
LONG nError = RegQueryValueEx(hKey, lpValue, NULL, &type, (LPBYTE)&data, &size);
if (nError==ERROR_FILE_NOT_FOUND)
data = 0; // The value will be created and set to data next time SetVal() is called.
else if (nError)
cout << "Error: " << nError << " Could not get registry value " << (char*)lpValue << endl;
return data;
}
用于写入/读取字符串值的代码(在注册表中存储为中文字符):
void SetVal(HKEY hKey, LPCTSTR lpValue, string data)
{
LONG nError = RegSetValueEx(hKey, lpValue, NULL, REG_SZ, (LPBYTE)&data, sizeof(data));
if (nError)
cout << "Error: " << nError << " Could not set registry value: " << (char*)lpValue << endl;
}
string GetVal(HKEY hKey, LPCTSTR lpValue)
{
string data; DWORD size = sizeof(data); DWORD type = REG_SZ;
LONG nError = RegQueryValueEx(hKey, lpValue, NULL, &type, (LPBYTE)&data, &size);
if (nError==ERROR_FILE_NOT_FOUND)
data = "0"; // The value will be created and set to data next time SetVal() is called.
else if (nError)
cout << "Error: " << nError << " Could not get registry value " << (char*)lpValue << endl;
return data;
}
答案 0 :(得分:0)
您的代码存在的问题是您天真地将string
类型变量转换为LPBYTE
。
这是您的代码更正:
void SetVal(HKEY hKey, LPCTSTR lpValue, string data)
{
const char *x = data.c_str();
LONG nError = RegSetValueEx(hKey, lpValue, NULL, REG_SZ, (LPBYTE)data.c_str(), data.size());
if (nError)
cout << "Error: " << nError << " Could not set registry value: " << (char*)lpValue << endl;
}
string GetVal(HKEY hKey, LPCTSTR lpValue)
{
string data;
#define MAXLENGTH 100
char buffer[100];
DWORD size = sizeof(buffer);
DWORD type = REG_SZ;
LONG nError = RegQueryValueEx(hKey, lpValue, NULL, &type, (LPBYTE)buffer, &size);
if (nError == ERROR_FILE_NOT_FOUND)
{
data = "0"; // The value will be created and set to data next time SetVal() is called.
return data;
}
else if (nError)
cout << "Error: " << nError << " Could not get registry value " << (char*)lpValue << endl;
data = buffer;
return data;
}
仍有改进的余地,例如最大字符串长度限制为100,并且应该改进错误处理。
<强>说明:强>
这是SetVal
RegSetValueEx(hKey, lpValue, NULL, REG_DWORD, (LPBYTE)&data, sizeof(DWORD));
data
投射到LPBYTE
。sizeof(DWORD)
错误,因为您需要提供字符串的长度这是GetVal
中的代码:
string data;
DWORD size = sizeof(data);
DWORD type = REG_SZ;
LONG nError = RegQueryValueEx(hKey, lpValue, NULL, &type, (LPBYTE)&data, &size);
sizeof(data)
当data
为string
时没有任何意义。它不是字符串的长度,在那一刻它是0。
string
LPBYTE
天真地投射到RegQueryValueEx