Why
perror
是Unix标准错误处理函数,提供错误代码到可读的错误描述的转换,在Windows中,需要使用FormatMessage
将GetLastError
返回的错误代码格式化。
long Perror(_TCHAR *op) {
_TCHAR *bufMsg = NULL;
long code = GetLastError();
if (code == 0) {
_tprintf(_T("OP "%s" succeed!
"), op);
return code;
}
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM,
NULL,
code,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPTSTR)&bufMsg,
0, NULL);
_tprintf(_T("OP "%s" failed with code %d: %s"/*bufMsg自带换行*/), op, code, bufMsg);
SetLastError(0);
LocalFree(bufMsg);
return code;
}
also
不要使用LocalFree,使用HeapFree函数。