写日志(注意不要用CString)

来源:互联网 发布:淘宝秒杀回答问题技巧 编辑:程序博客网 时间:2024/05/17 06:23

因为CString不是安全的,当程序非正常结束时,有可能产生内存泄露

void WriteToLog(CString strInfo, CString fileName)
{
 try  
 {
  
  char path[512];
  ::GetModuleFileName(NULL, path, 512);
  int len = strlen(path);
  for (int i=len; i>0; i--)
  {
   if ('//' == path[i])
   {
    path[i] = '/0';
    break;
   }
  }
  
  strcat(path, _T("//"));
  strcat(path, fileName);
  
  char   tmpStr[512];
  ZeroMemory(tmpStr, 512);  
  CTime   mTime;  
  mTime=CTime::GetCurrentTime();
  sprintf(tmpStr, _T("%04d-%02d-%02d %02d:%02d:%02d      %s/r/n"), mTime.GetYear(),  
   mTime.GetMonth(),  
   mTime.GetDay(),  
   mTime.GetHour(),  
   mTime.GetMinute(),  
   mTime.GetSecond(),  
   strInfo); 
  
  
  
  int   nLen=strlen(tmpStr);  
  TCHAR*   tBuf = tmpStr;
  
  CFile   file;
  
  if (file.Open(path,CFile::modeCreate |CFile::modeNoTruncate | CFile::modeWrite, NULL))
  {
   file.SeekToEnd();
   file.Write(tBuf,nLen*sizeof(TCHAR));
   file.Close();  
  }
 }  
 catch   (...)  
 {  
  TRACE(_T("WriteToLog/n"));  
 }
}