Skip to content

Instantly share code, notes, and snippets.

@aianau
Last active June 7, 2019 09:02
Show Gist options
  • Save aianau/d08e4c736edc5ffb8c0f89ececdb2d7c to your computer and use it in GitHub Desktop.
Save aianau/d08e4c736edc5ffb8c0f89ececdb2d7c to your computer and use it in GitHub Desktop.
Prints last error by GetLastError(), FormatMessageA().
#include <stdlib.h>
#include "windows.h"
void PrintLastError()
{
//Get the error message, if any.
DWORD errorMessageID = ::GetLastError();
if (errorMessageID == 0)
{
return; //No error message has been recorded
printf("No error.\n");
}
LPSTR messageBuffer = nullptr;
size_t size = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
NULL, errorMessageID, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)& messageBuffer, 0, NULL);
printf("%s\n", messageBuffer);
//Free the buffer.
LocalFree(messageBuffer);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment