Click here to Skip to main content
15,917,005 members
Please Sign up or sign in to vote.
2.50/5 (2 votes)
See more:
I have created a registry entry and want to read it through C program.
But the RegQueryValueEx() function is failing and I am not seeing any error.
I directly get the command prompt.

Here is the code snippet:
#define REG_KEY          TEXT("Software\\MyCompany\\XYZ")    // XYZ is also a key and 
                                                                has a default value 
                                                                REG_SZ in it

HKEY hKey;
LONG lResult;
DWORD BufferSize = MAX_PATH;
DWORD dwValue, dwSize = sizeof(dwValue);

	_tprintf( _T("\nInside delOEMInf.") );

                                          &hKey)) == ERROR_SUCCESS)
                _tprintf( _T("\ RegOpenKeyEx  OPENED"));

		lResult = RegQueryValueEx(hKey, "", NULL, NULL, (LPBYTE)&dwValue, BufferSize);
                _tprintf( _T("\nRegQueryValueEx %d"), lResult);
                RegCloseKey( hKey);

I get only the first printf "RegOpenKeyEx OPENED".
The second printf does not gets printed and I see directly the command prompt.
I am not abel to get the return value of regqueryvalueex().

What might be the issue and how to debug and resolve it?
chandanadhikari 23-Apr-12 2:35am    
may be the code does not have the permission to read from the registry.Please check if the key really exists in the registry. What does the command prompt say when it comes up ?
barneyman 23-Apr-12 21:49pm    
DON'T open HKLM with ALL_ACCESS for reading - win7 will fail on you

You are passing the address of a DWORD value as output buffer and the address MAX_PATH as pointer to the size parameter. But RegQueryValueEx requires the address of a buffer that can hold the data specified by the lpcpData parameter which must be passed as address of a DWORD to receive the data length read from the registry.

So you have an access violation and a buffer overrun.

A workin code would look like:
char lpszBuffer[MAX_PATH];
RegQueryvalueEx(hKey, "", NULL, NULL, LPBYTE(lpszBuffer), &dwSize); 
Share this answer
nv3 23-Apr-12 9:18am    
Why do some people simply ignore the reference information that is freely available in MSDN! 5ed.
From MSDN:[^]

Return value
If the function succeeds, the return value is ERROR_SUCCESS.
If the function fails, the return value is a nonzero error code defined in Winerror.h. You can use the FormatMessage function with the FORMAT_MESSAGE_FROM_SYSTEM flag to get a generic description of the error.

ERROR_SUCCEESS is zero, so RegOpenKeyEx is apparently failing. Use FormatMessage, and you'll get a hint of the reason.

Hope this helps,
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900