【winapi】FormatMessage函数的使用

概述:FormatMessage 函数的使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
const char* SPErrMsg(int errcode)
{
static char _g_inner_msg[1024];
memset(_g_inner_msg, 0, sizeof(_g_inner_msg));

#if SP_PLATFORM==SP_PLATFORM_WINDOWS
if (0==errcode)
{
errcode = GetLastError();
}
LPTSTR buf = NULL;
if (::FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
NULL, errcode, MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US) /* MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT) */,
(LPTSTR)&buf, 0, NULL))
{
// DWORD language_id
// MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT)
// MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US)
// MAKELANGID(LANG_CHINESE_SIMPLIFIED, SUBLANG_CHINESE_SIMPLIFIED)
// MAKELANGID(LANG_CHINESE_TRADITIONAL, SUBLANG_CHINESE_TRADITIONAL)

int len = snprintf(_g_inner_msg, sizeof(_g_inner_msg), " [%d]%s", errcode, buf);
if ( len>2 && _g_inner_msg[len-1]=='\n' && _g_inner_msg[len-2]=='\r' )
{
_g_inner_msg[len - 1] = '\0';
_g_inner_msg[len - 2] = '\0';
}
::LocalFree(buf);
}
else
{
snprintf(_g_inner_msg, sizeof(_g_inner_msg), " [%d]Unknown error %d", errcode, errcode);
}
#else
// https://stackoverflow.com/questions/3219393/stdlib-and-colored-output-in-c
if (0==errcode)
{
errcode = errno;
errno = errcode;
}
snprintf(_g_inner_msg, sizeof(_g_inner_msg), " [%d]%s", (int)errcode, strerror(errcode));
#endif
return (_g_inner_msg);
}

【winapi】FormatMessage函数的使用
https://hodlyounger.github.io/A_OS/Windows/API/【winapi】FormatErrMessage/
作者
mingming
发布于
2023年10月27日
许可协议