您的位置:首页 > 其它

我的调试输出 _TRACE 第三版

2015-06-05 05:36 344 查看
在第二版的基础上增加了非法检查功能 另外使用_WINDOWS宏来区分控制台和Windows程序

#include <stdlib.h>
#include <stdio.h>
#include <crtdbg.h>
class __CTrace
{
#ifdef _WINDOWS
#define dbgOutputA(str) OutputDebugStringA(str)
#define dbgOutputW(str) OutputDebugStringW(str)
#else
#define dbgOutputA(str) printf_s("%s", str)
#define dbgOutputW(str) wprintf_s(L"%s", str)
#endif

#if (defined UNICODE || defined _UNICODE)
#define dbgOutput dbgOutputW
#else //ASNI
#define dbgOutput dbgOutputA
#endif

LPCTSTR szFileName;
int fileLine;
_invalid_parameter_handler oldHandler;
int oldCrtAssertMode;

static void TraceInvalidParameterHandler(const wchar_t* expression,
const wchar_t* function, const wchar_t* file, unsigned int line, uintptr_t pReserved)
{
wchar_t wchBuffer[1024];
swprintf_s(wchBuffer,
L"Invalid trace parameter detected in function %s, file %s(%d), Expression: %s\r\n",
function, file, line, expression);
dbgOutputW(wchBuffer);
}

public:
__CTrace(LPCTSTR szFile, int nLine)
{
szFileName = szFile;
fileLine = nLine;

//Disable invalid format assert error
oldHandler = _set_invalid_parameter_handler(TraceInvalidParameterHandler);
// Disable the message box for assertions.
oldCrtAssertMode = _CrtSetReportMode(_CRT_ASSERT, 0);
}

virtual ~__CTrace()
{
_CrtSetReportMode(_CRT_ASSERT, oldCrtAssertMode);
_set_invalid_parameter_handler(oldHandler);
}

void __cdecl operator()(LPCTSTR format, ...) const
{
int ivsp, iLen = 0;
TCHAR szDbgOut[4096];

iLen += _stprintf_s(szDbgOut + iLen, _countof(szDbgOut) - iLen,
_T("%s(%d) "), szFileName, fileLine);

va_list arg;
va_start(arg, format);
ivsp = _vstprintf_s(szDbgOut + iLen, _countof(szDbgOut) - iLen,  format, arg);
va_end(arg);
if(ivsp < 0  && errno == EINVAL)
{
_tcscpy_s(szDbgOut + iLen, _countof(szDbgOut) - iLen,
_T("Invalid trace parameter detected\r\n"));
}

dbgOutput(szDbgOut);
}
};

#ifdef _DEBUG
#define _TRACE __CTrace(_T(__FILE__), __LINE__)
#else
#define _TRACE(...)  __noop
#endif


测试代码

_TRACE(_T("myTrace %d\n"), 10);

_TRACE(_T("%\n"), 10);

调试输出

d:\vc_project\dlg3\dlg3\dlg3.cpp(106) myTrace 10

Invalid trace parameter detected in function _woutput_s_l, file f:\dd\vctools\crt_bld\self_x86\crt\src\output.c(1120), Expression: ("Incorrect format specifier", 0)

d:\vc_project\dlg3\dlg3\dlg3.cpp(107) Invalid trace parameter detected
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: