现在的位置: 首页 > 综合 > 正文

MFC 在一个项目中添加log文件的读写操作问题

2014年12月12日 ⁄ 综合 ⁄ 共 2579字 ⁄ 字号 评论关闭

整体使用类进行封装文件读写的操作

//头文件

#pragma once
#include "afx.h"

class CLogProcedure
{
 public:
  CLogProcedure(void);
  ~CLogProcedure(void);
  static voidCreateLogFile();//文件的创建与打开操作值得注意的是要进行的文件打开操作,只能打开一次,那就要求设置静态的变量去标识文件的状态
  static void WriteLogFile( DWORDdwErrorLevel, LPCTSTR lpOutputString, LPCTSTR lpfunc, INT iline);//对文件进行的写操作,在程序中需要注意的是CStdioFile类的静态设置
  
  enum E_LOG_OUTPUT_LEVEL
  {
   E_LOGLEVEL_FAILED= -1 ,
   E_LOGLEVEL_INFORMATION= 0 ,
   E_LOGLEVEL_SUCCEEDED= 1
  };

 private:
  static CStdioFilem_plogFile;

};

 

//CPP

#include "StdAfx.h"
#include
#include "LogProcedure.h"

CStdioFile CLogProcedure::m_plogFile;//

CLogProcedure::CLogProcedure(void)
{
 //CreateLogFile();//创建日志文件
}

CLogProcedure::~CLogProcedure(void)
{

}

void CLogProcedure::CreateLogFile()
{
 #define MAX_PATH_SIZE (0x100)
 static BOOL bInited = false;//静态变量只会被初始化一次

 if( false == bInited )
 {
  TCHARtcPath[MAX_PATH_SIZE];
  GetModuleFileName(NULL, tcPath,MAX_PATH_SIZE);//检索当前进程所执行的可执行文件的路径,就是获得当前可执行文件的路径

  CStringfilename(tcPath);
  CString strLogName(tcPath);
  CString strLogDir;
  INT index =filename.ReverseFind(_T('\\'));//返回的是该字符串所在的位置索引
  if( -1 != index )
  {
   INT len =filename.GetLength();
   ++index;
   filename.Delete(index,len - index);//这样就找到了可执行文件的名字了
   strLogDir =filename;
   strLogDir +=_T("Log\\");
   CreateDirectory(strLogDir,NULL);//成功的话返回值非零
   CStringstrTemp;
   strLogName.Delete(0,index);
   strTemp =strLogName.Mid(0,strLogName.ReverseFind(_T('.')));//返回值是整体到点结束的字符串
   time_tnowTime;
   time(&nowTime);//添加此时的秒数
   strLogName.Format(_T("Log\\RUN_%s_%d_LOG.txt"),strTemp, nowTime);//定义文件log的名称是。。。
  }

  filename +=strLogName;//文件名称的路径
  if( m_plogFile.Open( filename,CFile::modeCreate |\
        CFile::modeNoTruncate|\
        CFile::shareDenyWrite|\
        CFile::modeWrite) )//用这样的模式进程创建或者检查文件名称的路径
  {
   bInited =true;//然后给标志一个新的标志,对此标志进行判断的时候就可以防止(在多次进行写入该次程序运行的时候多个地方的log信息)多次打开文件log文件
  }

 }
}

void CLogProcedure::WriteLogFile( DWORD dwErrorLevel, LPCTSTRlpOutputString, LPCTSTR lpfunc, INT iline )
{
 CreateLogFile();//创建日志文件

 char* org = _strdup( setlocale(LC_CTYPE,NULL));//为setlocale(LC_CTYPE,NULL)分配空间副本
 setlocale( LC_CTYPE,"chs" );//支持简体中文

 CString strErrorLevelInfo;
 switch(dwErrorLevel)
 {
 case E_LOGLEVEL_FAILED:
  strErrorLevelInfo =_T("FAILED");
  break;
 case E_LOGLEVEL_SUCCEEDED:
  strErrorLevelInfo =_T("SUCCEEDED");
  break;
 case E_LOGLEVEL_INFORMATION:
  strErrorLevelInfo =_T("INFOMATION");
  break;
 default:
  strErrorLevelInfo =_T("OTHER");
  break;
  }

 CString outputLog;
 outputLog.Format(_T("The [%s]: at [%d] line--> %s + %s\r\n"), //文件内容的格式
 lpfunc,
 iline,
 strErrorLevelInfo,
 lpOutputString);

 m_plogFile.WriteString(outputLog);
 m_plogFile.Flush();//强制缓冲区的内容写入指定文件
 setlocale( LC_CTYPE, org );
 free( org );

 return;
}

抱歉!评论已关闭.