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

 

 

 

posted @   一点一滴的Beer  阅读(2870)  评论(0编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架
点击右上角即可分享
微信分享提示