Answer the question
In order to leave comments, you need to log in
How to correctly pass in RegSetValueEx to lpData NULL?
The crux of the matter is what. I wrote a function like this:
bool modifyKey(HKEY _hKey, wstring path, LPCWSTR name, LPCWSTR value) {
HKEY hKey;
if (RegOpenKey(_hKey, path.data(), &hKey) == ERROR_SUCCESS) {
if (RegSetValueEx(hKey, name, NULL, REG_SZ, (BYTE*)value, sizeof(value)) == ERROR_SUCCESS) {//SIZEOF(VALUE), сюда не смотреть, я уже пробовал по разному и оставил так.
return RegCloseKey(hKey) == ERROR_SUCCESS;
}
else {
RegCloseKey(hKey);
}
}
else {
if (RegCreateKey(_hKey, path.data(), &hKey) == ERROR_SUCCESS) {
if (RegSetValueEx(hKey, name, NULL, REG_SZ, (BYTE*)value, sizeof(value)) == ERROR_SUCCESS)//SIZEOF(VALUE), сюда не смотреть, я уже пробовал по разному и оставил так. {
return RegCloseKey(hKey) == ERROR_SUCCESS;
}
else {
RegCloseKey(hKey);
}
}
}
return false;
}
Answer the question
In order to leave comments, you need to log in
Let's start simple.
sizeof( expresion )
allows you to find out the minimum allowed amount of memory required in order for the memory to hold an object with an assertion result type of expresion
.
sizeof( value )
will return the size LPCWSTR
, i.e. type size const wchar_t*
.
wcslen
does not allow zero to be passed as its parameter. It is entirely up to you to take care of this.
RegSetValueExW
can take zero in the parameter lpData
, but then it cbData
must contain 0
. But in general, this is a very bad practice. If you need to write an empty string, write an empty one. line. Those. ""
, but not zero.
cbData
must be given by the size of the string buffer in bytes, including the terminal character, or both terminal characters in the case of a multiline argument in lpData
. An important note is that the cbData
size is indicated in bytes, not in characters. You are lpData
passing a string from wchar_t
, the size of which is more than one byte.
Further, according to the code itself. Its hard to read.
bool modifyKey( HKEY root_hey, const std::wstring_view& path, const std::wstring_view& key_name, const std::wstring_view& new_value )
{
HKEY folder_key;
if( RegCreateKeyW( root_hey, path.data(), &folder_key ) != ERROR_SUCCESS )
{
return false;
}
const BYTE* const value_buffer = reinterpret_cast<const BYTE*>( new_value.data() );
const DWORD buffer_size = static_cast<DWORD>( new_value.length() * sizeof( wchar_t ) + 1 );
if( RegSetValueExW( folder_key, key_name.data(), 0, REG_SZ, value_buffer, buffer_size ) != ERROR_SUCCESS )
{
RegCloseKey( folder_key );
return false;
}
if( RegFlushKey( folder_key ) != ERROR_SUCCESS )
{
RegCloseKey( folder_key );
return false;
}
RegCloseKey( folder_key );
return true;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question