0
如何在C++中寫入/讀取Windows註冊表中的字符串?在C++的註冊表中寫入/讀取字符串
我能夠使用以下代碼在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;
}
時,你可以張貼[MCVE]你又天真地鑄造
string
到LPBYTE
。 –當處理以空字符結尾的字符串時,'sizeof(DWORD)'是錯誤的。它返回一個DWORD(指針?)的大小,而不是字符串的長度。除非你寫一個很短的字符串,否則這個值太小了。你也不是null結束你的字符串。 –
您發佈了讀取/寫入DWORD值的代碼,而不是讀取/寫入字符串值失敗的代碼。 –