用CStdioFile写程序日志

用CStdioFile写程序日志
假定日志保存在应用程序目录下,文件名为logfile.log
调用下面的函数获得当前应用程序的目录,
/* */
/* Function name : GetAppDir */
/* Description : Get application directory. */
/* */
/********************************************************************/
void GetAppDir(CString& strAppDir)
{
 TCHAR szFullPath[MAX_PATH];
 TCHAR szDir[_MAX_DIR];
 TCHAR szDrive[_MAX_DRIVE];
 // Get application's full path.
 ::GetModuleFileName(NULL, szFullPath, MAX_PATH);
 TRACE(_T("%s/n"),szFullPath);
 // Break full path into seperate components.
 _splitpath(szFullPath, szDrive, szDir, NULL, NULL);
 
 // Store application's drive and path
 strAppDir.Format(_T("%s%s"), szDrive, szDir);
}
然后使用类似下面的函数写日志
void CLogTestDlg::OnButton1()
{
 // TODO: Add your control notification handler code here
 CStdioFile f;
 CString strApp;
 GetAppDir(strApp);
 CString strLogFileName;
 strLogFileName=strApp+"logfile.log";

 BOOL bResult=f.Open(strLogFileName,CFile::modeWrite|CFile::modeCreate|CFile::modeNoTruncate|CFile::typeText) ;
 if (!bResult)
 {
  TRACE("Open error /n");
  return;
 }
 CTime t=CTime::GetCurrentTime();
 static i=0;
 CString strWrite;
 strWrite.Format("[%04d-%02d-%02d %02d:%02d:%02d]this is test string %d/n",t.GetYear(),t.GetMonth(),t.GetDay(),t.GetHour(),t.GetMinute(),t.GetSecond(),i++);
 f.SeekToEnd();
 f.WriteString(strWrite);
 f.Close();
}
注意的地方:
1.打开文件的时候要加上CFile::modeCreate|CFile::modeNoTruncate,其中CFile::modeCreate的作用在文件不存在的时候创建文件,
  CFile::modeNoTruncate的作用是不将文件的长度截断为0,如果不加modeNoTruncate,每次打开文件后,文件会被截断为0
2.写文件之前一定要SeekToEnd,否则以前的内容会被覆盖。
3.写完之后关闭文件

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值