// EM - Error Message class
// Used to avoid memory leaks
#include "stdafx.h"
#include <windows.h>
const DWORD MAX_LEN = 256;
class EM
{
LPTSTR lpBuf; // from call
DWORD dwErr; // current err
private:
// Helper function
void Init(void)
{
int len; // message len
len = FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
NULL,
dwErr,
MAKELANGID(LANG_NEUTRAL,
SUBLANG_DEFAULT),
(LPTSTR)&lpBuf,
MAX_LEN,
NULL);
if (! len)
lpBuf = NULL;
}
public:
inline EM()
{
dwErr = GetLastError();
Init();
}
inline EM(const DWORD dwE) : dwErr(dwE) { Init(); }
inline ~EM() { LocalFree(lpBuf); }
inline operator LPCTSTR() const
{ return LPCTSTR(lpBuf); }
inline operator LPTSTR() const { return lpBuf; }
inline operator DWORD() const { return dwErr; }
};
int main(int argc, char* argv[])
{
// print error messages
// for error codes 0-9
for (DWORD i = 0; i < 10; ++i)
{
EM em(i);
if (LPCTSTR(em))
printf("%5d %s", DWORD(i), LPTSTR(em));
}
// show default behaviour
printf("\nGenerate an error by creating an invalid
directory.\n\n");
CreateDirectory("*BadName*", 0);
EM em; // capture system error
printf("Code=%d Text=%s\n", DWORD(em), LPTSTR(em));
return 0;
}