Skip to content

Instantly share code, notes, and snippets.

@daxliar
Last active May 16, 2018 18:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save daxliar/495ba681b2dc341f9a7f56c418e58c9f to your computer and use it in GitHub Desktop.
Save daxliar/495ba681b2dc341f9a7f56c418e58c9f to your computer and use it in GitHub Desktop.
Create a string with last error message
// Needs Windows constant and type definitions
#include <windows.h>
#include <string>
// Create a string with last error message
std::string GetLastErrorStdStr()
{
DWORD error = GetLastError();
if (error)
{
LPVOID lpMsgBuf;
DWORD bufLen = FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
error,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPTSTR) &lpMsgBuf,
0, NULL );
if (bufLen)
{
LPCSTR lpMsgStr = (LPCSTR)lpMsgBuf;
std::string result(lpMsgStr, lpMsgStr+bufLen);
LocalFree(lpMsgBuf);
return result;
}
}
return std::string();
}
std::wstring GetLastErrorStdStrW()
{
DWORD error = GetLastError();
if (error)
{
LPVOID lpMsgBuf;
DWORD bufLen = FormatMessageW(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
error,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPTSTR) &lpMsgBuf,
0, NULL );
if (bufLen)
{
LPCWSTR lpMsgStr = (LPCWSTR)lpMsgBuf;
std::wstring result(lpMsgStr, lpMsgStr+bufLen);
LocalFree(lpMsgBuf);
return result;
}
}
return std::wstring();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment