Newbie
Newbie

Reputation: 1613

RegQueryValueEx() always returns only 4 bytes of the string

What im doing wrong this time? The following code always returns 4 bytes only, instead of the whole string:

HKEY hkey;
DWORD dwType, dwSize;

char keybuffer[512];

if(RegOpenKeyEx(HKEY_CURRENT_USER, TEXT("software\\company name\\game name"), 0, KEY_READ, &hkey) == ERROR_SUCCESS){
    dwType = REG_SZ;
    dwSize = sizeof(keybuffer);
    RegQueryValueEx(hkey, TEXT("setting"), NULL, &dwType, (PBYTE)&keybuffer, &dwSize);
    RegCloseKey(hkey);
}

Even if i change dwSize to anything, it will still return 4 bytes.

Edit: Apparently there was no bug in above code, but somewhere else -_-

Upvotes: 0

Views: 2946

Answers (4)

Hans Passant
Hans Passant

Reputation: 942000

I remember the registry key name from a previous question. You had a problem creating the value. In that thread, the value was created as a DWORD, 4 bytes. That's too much of a coincidence. Run Regedit.exe and navigate to the key you created and check what the value type is. If it is still a DWORD, you'll never get more than 4 bytes back, even if you ask for a string.

Fix the code that creates the value, make sure you create a REG_SZ, not a REG_DWORD. Use Regedit.exe to delete the old value before you run the code.

Upvotes: 3

Francis
Francis

Reputation: 12018

Maybe not an answer, but...

  1. you don't need to assign dwType = REG_SZ, because dwType is a output param.
  2. you can use NULL to replace (PBYTE)&keybuffer to see how much space does it want
  3. are you sure HKEY_CURRENT_USER is correct, or LOCAL_MACHINE? And is "setting" in REG_SZ for both CURRENT_USER and LOCAL_MACHINE, if you have both of them?
  4. check the return value of RegQueryValueEx.

Upvotes: 1

bk1e
bk1e

Reputation: 24328

I see two more potential pitfalls here. First, as Francis mentioned, you should check the return value. Do the 4 bytes actually correspond to the string characters you expect? They might be anything. From the documentation:

If the buffer specified by lpData parameter is not large enough to hold the data, the function returns ERROR_MORE_DATA and stores the required buffer size in the variable pointed to by lpcbData. In this case, the contents of the lpData buffer are undefined.

The second potential pitfall is that you're using a char array with a function that takes TCHAR parameters. If you're compiling for Unicode, the compiler will happily let you write a wide string to your narrow string buffer, due to the cast to PBYTE. It's safer to either use TCHAR consistently or don't use it at all (i.e. call RegQueryValueExA or RegQueryValueExW).

Upvotes: 0

Ation
Ation

Reputation: 11

(PBYTE)&keybuffer - wrong. must be (PBYTE)keybuffer.

Upvotes: 1

Related Questions