Skip to content

Instantly share code, notes, and snippets.

@ssendeavour
Created July 23, 2014 15:01
Show Gist options
  • Save ssendeavour/834467c95b34384bd8e3 to your computer and use it in GitHub Desktop.
Save ssendeavour/834467c95b34384bd8e3 to your computer and use it in GitHub Desktop.
show Windows API error text corresponding to number retured by GetLastError. source: http://msdn.microsoft.com/en-us/library/windows/desktop/bb540534(v=vs.85).aspx
void DisplayError(LPTSTR lpszFunction)
// Routine Description:
// Retrieve and output the system error message for the last-error code
{
LPVOID lpMsgBuf;
LPVOID lpDisplayBuf;
DWORD dw = GetLastError();
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
dw,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPTSTR) &lpMsgBuf,
0,
NULL );
lpDisplayBuf =
(LPVOID)LocalAlloc( LMEM_ZEROINIT,
( lstrlen((LPCTSTR)lpMsgBuf)
+ lstrlen((LPCTSTR)lpszFunction)
+ 40) // account for format string
* sizeof(TCHAR) );
if (FAILED( StringCchPrintf((LPTSTR)lpDisplayBuf,
LocalSize(lpDisplayBuf) / sizeof(TCHAR),
TEXT("%s failed with error code %d as follows:\n%s"),
lpszFunction,
dw,
lpMsgBuf)))
{
printf("FATAL ERROR: Unable to output error code.\n");
}
_tprintf(TEXT("ERROR: %s\n"), (LPCTSTR)lpDisplayBuf);
LocalFree(lpMsgBuf);
LocalFree(lpDisplayBuf);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment