user187
user187

Reputation: 19

How can I solve the problem when reading a registry entry?

i want to get the value from an registry entry. Here is my code:

#include <atlbase.h>
#include <atlstr.h>
#include <iostream>
#define BUFFER 8192
int main()
{
    char value[255];
    DWORD BufferSize = BUFFER;
    RegGetValue(HKEY_LOCAL_MACHINE, L"SYSTEM\\CurrentControlSet\\Control\\ComputerName\\ActiveComputerName", L"ComputerName", RRF_RT_REG_SZ, NULL, (PVOID)&value, &BufferSize);
    std::cout << value << std::endl;
}

My Computer name is: DESKTOP-IGW3F. But if i run my program my output is: D

I have no idea how to fix it...i hope you can help me.

Upvotes: 0

Views: 99

Answers (1)

Louis Bernard
Louis Bernard

Reputation: 279

The Win32 function RegGetValue() does not exist. It is only a preprocessor macro that will resolve to either RegGetValueA() or RegGetValueW() depending on your project settings. In your case, the macro resolves to RegGetValueW(), therefore it treats the registry value as a Unicode string (2 bytes per character). But you are using a char (1 byte per character) buffer to receive the Unicode data.

To make your code work, you need to either explicitly call RegGetValueA() instead, or change your buffer type from char to wchar_t. Either way, you should also check the return value of the function.

A working example could look like this:

#include <windows.h>
#include <iostream>

int main() 
{
    WCHAR value[255];
    DWORD bufferSize = 255 * sizeof(WCHAR);

    if (!RegGetValueW(HKEY_LOCAL_MACHINE, L"SYSTEM\\CurrentControlSet\\Control\\ComputerName\\ActiveComputerName", L"ComputerName", RRF_RT_REG_SZ, NULL, value, &bufferSize))
    {
        std::wcout << value << std::endl;
    }
}

Upvotes: 1

Related Questions