Search code examples
cwinapiregistry

Opening registry key in c


I have create a key using regedit, now I want to get its value. It doesn't give any error but it isn't showing anything. Code :

int main() {
    HKEY hKey;
    RegOpenKeyEx(HKEY_LOCAL_MACHINE, L"Ehsan Akbari", 0, KEY_ALL_ACCESS, &hKey);
    TCHAR sz[50];
    DWORD size = 50,type;
    RegEnumValue(hKey, 0, L"test", &size, NULL, &type, (LPBYTE)sz, &size);
    RegCloseKey(hKey);
    getch();
    return 0;
}

An image of regedit :picture

What am I doing wrong?

Edit


When I debugged I saw that hKey is NULL, but GetLastError doesn't report anything.


Solution

  • Here are the immediate problems that I can see:

    1. You detect no errors because you don't check for errors. Read the documentation for each function. The error code is returned in the return value.
    2. You ask for KEY_ALL_ACCESS which won't be granted under HKLM. You need to request just read access KEY_READ.
    3. Your screenshot shows the key has been created under HKCU, and you're trying to open it under HKLM.
    4. RegEnumValue expects the size of the data buffer in bytes. You pass the length, the number of characters.
    5. You are mixing Unicode literals and TCHAR. This is pointless. Your code won't compile targeting MBCS and in any case you don't care about Win98 any more. Stop using TCHAR and use wchar_t instead.
    6. The lpValueName parameter must be a modifiable buffer. You pass a literal. Remember that this function enumerates values. It does not read specific named values as perhaps you expect.
    7. The lpcchValueName parameter contains the size of the buffer you passed to lpcchValue in characters. You pass the length of the data buffer.
    8. The data returned may not be null terminated. You must protect against this as described in the documentation.
    9. For a C program which ignores its arguments, the correct main is int main(void).

    I expect there are more errors but I stopped looking at this point. I recommend you spend some quality time with the documentation.