views:

482

answers:

5

RegOpenKeyEx()

I want to printf("Success") or printf("Failure") depending on if the function fails or succeeds

How would I do such a conditional while keeping it neat and legible?

I am wanting to stay away from this :

if (RegOpenKeyEx(HKEY_LOCAL_MACHINE,"HUGE LONG KYEY STRUCTURE HERE",0,KEY_SET_VALUE) != 0 )
{
   //CODE 
}
A: 

It does not return ERROR_SUCCESS when it does not succeed. Is that what you mean?

for multiple checks of error codes use:

LONG errors = 0;

errors += abs( RegKeyOpenEx(HKEY_LOCAL_MACHINE,"HUGE LONG KYEY STRUCTURE HERE",0,KEY_SET_VALUE) );
errors += abs( RegKeyOpenEx(HKEY_LOCAL_MACHINE,"HUGE LONG KYEY STRUCTURE HERE",0,KEY_SET_VALUE) );
errors += abs( RegKeyOpenEx(HKEY_LOCAL_MACHINE,"HUGE LONG KYEY STRUCTURE HERE",0,KEY_SET_VALUE) );
errors += abs( RegKeyOpenEx(HKEY_LOCAL_MACHINE,"HUGE LONG KYEY STRUCTURE HERE",0,KEY_SET_VALUE) );
errors += abs( RegKeyOpenEx(HKEY_LOCAL_MACHINE,"HUGE LONG KYEY STRUCTURE HERE",0,KEY_SET_VALUE) );

if( errors > 0 )
{
  print( "OMG It went wrong!\n" );
}
else
{
  print( "Hero!\n" );
}
Martlark
This returns error codes, not Boolean values, so you should watch out for integer overflows and positive/negative return values. Even Win32 API functions that return BOOL can return 1 or -1 in different situations (e.g. GetMessage).
bk1e
@bk1e - good point I was just a slacker
Martlark
@bk1e - but a look at winerror.h shows there are no negative error codes and overflow should be quite unlikely unless you are calling it more than a million times or so. Your concerns are unfounded and uneducated.
Martlark
+3  A: 

Are you asking how to check why it failed?

"A nonzero error code defined in Winerror.h indicates failure. To get a generic description of the error, call FormatMessage with the FORMAT_MESSAGE_FROM_SYSTEM flag set."

So.. ERROR_SUCCESS if succeeded, error code if it fails.

RobS
+1  A: 

After checking the unedited question, I think the only thing you can do is to break up the statement into multiple statements like this:

const char* regKey = "BIG_STRING......";
DWORD errorCode = RegOpenKeyEx(...);
if(ERROR_SUCCESS == errorCode)
{ 
  //Rest of the code
}
else
{
  //Error handling
}
Naveen
A: 

You could instead use the ternary operator:

bool success = (RegKeyOpenEx(...) == ERROR_SUCCESS);
printf("%s\n", success ? "Success" : "Failure");
Adam Rosenfield
+1  A: 

You can use newlines, or name things or both,

 LONG result = RegOpenKeyEx(HKEY_LOCAL_MACHINE,
                            "HUGE LONG KYEY STRUCTURE HERE",
                             0,KEY_SET_VALUE);
 if(result != 0 ) {
    ...

or perhaps

 LPCTSTR keypath = "HUGE LONG KYEY STRUCTURE HERE";
 if( RegOpenKeyEx(HKEY_LOCAL_MACHINE,keypath,0,KEY_SET_VALUE) != 0 ) {
     ...
Logan Capaldo