WinCE/C++/MFC异常日志记录
作用:在WinCE平台下,通过API获得当前执行文件的路径,并在当前路径中创建TXT异常日志,然后加上时间标记并写入内容。
CamException.h
#pragma once
class CamException
{
public:
CamException(void);
~CamException(void);
private:
static char* CString2char(CString &str,DWORD *outCharLength);//CString转char,因为VS2005中的字符问题比较纠结
static CString QueryExePath();//获得当前EXE程序的路径
public:
static void WriteToFile(CString exMsg);//采用MFC的方法获取系统时间 并 写入文件
};
CamException.cpp
#include "StdAfx.h"
#include "CamException.h"
CamException::CamException(void)
{
}
CamException::~CamException(void)
{
}
#pragma region //程序异常记录 全局代码块
//CString转char,因为VS2005中的字符问题比较纠结。
char* CamException::CString2char(CString &str,DWORD *outCharLength)
{
int len = str.GetLength();
*outCharLength = len * 2 + 1;
char* chRtn = (char*)malloc((*outCharLength)*sizeof(char));//CString的长度中汉字算一个长度
memset(chRtn, 0, *outCharLength);
USES_CONVERSION;
strcpy((LPSTR)chRtn,OLE2A(str.LockBuffer()));
return chRtn;
}
CString CamException::QueryExePath()
{
TCHAR path[MAX_PATH];
::GetModuleFileName(NULL,path,MAX_PATH);
CString p(path);
CString subp;
int nPos = p.ReverseFind('\\');
//ASSERT(-1!=nPos);
return p.Left(nPos+1);
}
//采用MFC的方法获取系统时间 并 写入文件
void CamException::WriteToFile(CString exMsg)
{
#pragma region //异常日志
SYSTEMTIME st;
CString strTimeTag;//时间标记
GetLocalTime(&st);
strTimeTag.Format(L"%4d-%2d-%2d %2d:%2d:%2d",st.wYear,st.wMonth,st.wDay,st.wHour,st.wMinute,st.wSecond);
CString strFullExMsg;//带时间标记的异常信息记录
strFullExMsg=strTimeTag + L" # " + exMsg;
DWORD dwCharLength;
char *pChar=CString2char(strFullExMsg,&dwCharLength);
#pragma endregion
CString strCurrentFolderPath=QueryExePath();
CFile hSaveFile;
hSaveFile.Open(strCurrentFolderPath+L"ErrorLog.txt",CFile::modeCreate | CFile::modeWrite |CFile::modeNoTruncate);//创立一个txt文件。
hSaveFile.SeekToEnd(); //文件末尾
hSaveFile.Write(pChar,dwCharLength);
hSaveFile.Write("\r\n",2);
hSaveFile.Close();
free(pChar);
pChar=NULL;
}
#pragma endregion

浙公网安备 33010602011771号