Win32 Perror

Why

perror是Unix标准错误处理函数,提供错误代码到可读的错误描述的转换,在Windows中,需要使用FormatMessageGetLastError返回的错误代码格式化。

long Perror(_TCHAR *op) {
	_TCHAR *bufMsg = NULL;
	long code = GetLastError();
    if (code == 0) {
        _tprintf(_T("OP \"%s\" succeed!\n"), 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函数。

END

posted @ 2021-02-23 18:12  develon  阅读(104)  评论(0编辑  收藏  举报