Skip navigation

Well, you konw there’s GetLastError(). But how can you get the last error AS A STRING? Use FormatMessage()!

/**

Please be sure to LocalFree() returned result when you are done
with the string returned.

*/
LPSTR GetLastErrorString()
{
  LPSTR buf = NULL ;

  int result = FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER |
                 FORMAT_MESSAGE_FROM_SYSTEM,
                 0,
                 GetLastError(),
                 0,
                 (LPSTR)&buf,
                 0,
                 0 );

  return buf ;
}

// Use above function with this one, so you don't have to
// worry about calling LocalFree
void printLastError( char *msg )
{
  LPSTR error = GetLastErrorString() ;
  printf( "%s %s\n", msg, error ) ;
  LocalFree( error ) ;
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: