生活随笔
收集整理的這篇文章主要介紹了
vc记录日志
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
vc2005寫日志類
頭文件:
// LogFile.h: interface for the CLogFile class.
//
// Remark:摘自網上一篇博客,改造了下
// Author: jiftle
// DateTime: 2012-01-17 15:14 臘月二十五
//#if !defined(AFX_LOGFILE_H__288388CA_9A3E_4F3D_A2B8_F1078E1F6A6B__INCLUDED_)
#define AFX_LOGFILE_H__288388CA_9A3E_4F3D_A2B8_F1078E1F6A6B__INCLUDED_#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000class CLogFile
{
public:CLogFile();virtual ~CLogFile();static CString GetFileName();static CString GetFilePath();static BOOL WriteLog(CString LogText);
};#endif // !defined(AFX_LOGFILE_H__288388CA_9A3E_4F3D_A2B8_F1078E1F6A6B__INCLUDED_)
源代碼:
// LogFile.cpp: implementation of the CLogFile class.
//
//#include "stdafx.h"
#include "LogFile.h"#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif//
// Construction/Destruction
//CLogFile::CLogFile()
{}CLogFile::~CLogFile()
{}
//獲取文件名稱
CString CLogFile::GetFileName()
{CString m_sFileName;m_sFileName = CTime::GetCurrentTime().Format("%Y-%m-%d") + _T(".log");return m_sFileName;
}
//獲取應用程序所在路徑
CString CLogFile::GetFilePath()
{ CString m_FilePath;GetModuleFileName(NULL,m_FilePath.GetBufferSetLength(MAX_PATH+1),MAX_PATH);m_FilePath.ReleaseBuffer();int m_iPosIndex;m_iPosIndex = m_FilePath.ReverseFind(_T('\\')); m_FilePath = m_FilePath.Left(m_iPosIndex) + _T("\\Log");return m_FilePath;
}BOOL CLogFile::WriteLog(CString LogText)
{try{CFile m_File;CStdioFile m_SFile;CFileFind m_FileFind;CString strLog;CString m_sFileName = GetFileName();CString m_sFilePath = GetFilePath();CString strTime = CTime::GetCurrentTime().Format(_T("[%Y-%m-%d %H:%m:%S] "));//組合寫入字符串strLog += strTime;strLog += LogText;if(!m_FileFind.FindFile(m_sFilePath)){CreateDirectory(m_sFilePath,NULL);}if(!m_SFile.Open(m_sFilePath + _T("\\") +m_sFileName,CFile::modeReadWrite)){m_SFile.Open(m_sFilePath + _T("\\") + m_sFileName,CFile::modeCreate | CFile::modeReadWrite | CFile::typeBinary);}m_SFile.SeekToEnd(); //written by jiftle 處理UNICODE下亂碼
#ifdef UNICODE CString strTmp = strLog;int len = 0;char *buf = NULL;len = WideCharToMultiByte(CP_ACP,0,strTmp,strTmp.GetLength(),NULL,0,NULL,NULL)+1;buf = new char[len];memset(buf,0,len);WideCharToMultiByte(CP_ACP,0,strTmp,strTmp.GetLength(),buf,len-1,NULL,NULL);
#elseCString strTmp = strLog;char *buf = NULL;int len=0;len = strTmp.GetLength()+1;//多分配一個存放結束符號buf = new char[len];memset(buf,0,len);buf=strTmp.GetBuffer();
#endifm_SFile.Write(buf,strlen(buf));m_SFile.Close();}catch(CFileException fileException){return false;}return true;
}
總結
以上是生活随笔為你收集整理的vc记录日志的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。