用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.写完之后关闭文件