开发者

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(hke开发者_如何学编程y);
}

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 -_-


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.


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


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.


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).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜