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;
}
を呼び出すときに
string
LPBYTE
に単純にキャストされています。 –ヌル終了文字列を扱うときに 'sizeof(DWORD)'が間違っています。文字列の長さではなく、DWORD(ポインタ?)のサイズを返します。あなたが非常に短い文字列を書いていない限り、値は非常に小さいです。あなたもあなたの文字列を終了するnullではありません。 –
失敗したコードの読み込み/書き込み文字列値ではなく、DWORD値の読み取り/書き込み用のコードを投稿しました。 –