Link to home
Start Free TrialLog in
Avatar of Paullkha
PaullkhaFlag for United States of America

asked on

RegOpenKeyEx REG_DWORD REG_SZ REG_BINARY

I know how to use RegOpenKeyEx.

The question is that all the examples I have seen seem to return data to character buffer. But if I have a key that stores REG_DWORD or REG_BINARY, why am I using a character buffer?

For instance, if I want a key called fileSize = 5000 stored as REG_DWORD, I would need to read it into a char buffer and then convert to a number, say using atoi?

So what is the point of REG_DWORD and REG_BINARY?

Avatar of Jaime Olivares
Jaime Olivares
Flag of Peru image

to read a DWORD:

DWORD dwData = 0;
DWORD bufSize = sizeof(DWORD);
               
RegQueryValueEx(main_key, "some entry", NULL, NULL, (LPBYTE)&dwData , &bufSize);
     
To read a binary is almost the same to read a string, with exception that no NULL character is added at the end of string.
Avatar of jkr
>>if I want a key called fileSize = 5000 stored as REG_DWORD, I would need to read it into a char buffer and then
>>convert to a number, say using atoi?

No, you'd use

DWORD ReadDWORD() {

    DWORD dwSample = 0; // 0 is the default
    HKEY hKey = NULL;
    REGSAM sam = KEY_READ;
    char* pszKey = "Software\\Blubb";

    if ( ERROR_SUCCESS != RegOpenKeyEx ( HKEY_LOCAL_MACHINE, pszKey, 0, sam, &hKey)) {

       return dwSample; // assume "default" if key is not present or readable

    } else {

        DWORD dwType = REG_DWORD;
        DWORD dwSize = sizeof ( DWORD);

        if ( ERROR_SUCCESS != RegQueryValueEx ( hKey, "ValueNAme", NULL, &dwType, ( LPBYTE) &dwSample, &dwSize)) {

            // error
        }
    }

    RegCloseKey ( hKey);

    return dwSample;
}

The same for 'REG_BINARY'.
ASKER CERTIFIED SOLUTION
Avatar of jkr
jkr
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
FYI:

RegQueryValueEx uses an unsigned char buffer (LPBYTE) to return values that could be text or binary data. When returning a DWORD it is returned as a binary number (32 bits) and *not* as text containing a number like "123456".

jkr and jaime both are casting the address of the output variable to LPBYTE, what is the usual way. However, you also could provide a byte buffer and copy the data in a second step, thus avoiding casts.

       unsigned char buf[32] = { '\0' };
       DWORD dwTyp = REG_DWORD;
       DWORD dwVal  = 0;
       DWORD dwSiz = sizeof(buf);

        if (RegQueryValueEx ( hKey, "Name", NULL, &dwTyp, buf, &dwSiz) == ERROR_SUCCESS &&
            dwSiz == sizeof(DWORD))
        {
             memcpy(&dwVal, buf, sizeof(DWORD));
        }

Regards, Alex
Avatar of Paullkha

ASKER

p.s. This is what made it all click:
DWORD dwSize = sizeof ( abSample);