This code gets Win32 error text. It is written to be read and understood on the first pass. Its arbitrary use of a static buffer is simply to not force one to remember to free the text it returns. It does sacrifice thread safety. It is also written to be a candidate for wrapping in __try/__except as well as try/catch exception handing. The use of objects such as CString would inhibit __try/__except vis-a-vis stack unwinding. Hopefully it's hard to break and easy to change.
#include <windows.h>
#include <tchar.h>
#include <stdio.h>
#include <conio.h>
char *GetErrorText(DWORD dwCode)
{
static char buff[2000] memset(buff,0,sizeof(buff));
char *pmsg;
SetLastError(0);
int nbytes = FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM, NULL, dwCode, MAKELANGID(LANG_NEUTRAL,SUBLANG_DEFAULT),
(LPTSTR)&pmsg,
sizeof(buff)-2,NULL);
DWORD dw = GetLastError();
if (dw==0) { strcpy_s(buff,pmsg);
LocalFree((HLOCAL)pmsg); }
return buff;
}
int main()
{
for (int code=0; code<2000000; code++)
{
-
if (strlen(msg))
{
printf("Win32 Code %3d: %s", code, msg); }
}
puts("\nPress any key to continue....");
while (!_kbhit()) Sleep(10);
}