1,实现日志记录到文件,支持日志文件大小限制,节省空间
void CController::LogWriteRecord(CString strText,CString strFileName)
{CStdioFile csFile;try{BOOL bRet = csFile.Open(strFileName,CFile::modeCreate|CFile::modeNoTruncate|CFile::modeReadWrite|CFile::shareDenyNone|CFile::typeText);csFile.SeekToEnd();CString strWriteText=strText+"\r\n";csFile.WriteString(strWriteText);//csFile.Write(strWriteText.GetBuffer(strWriteText.GetLength()),1);strWriteText.ReleaseBuffer();DWORD64 dwFileLen = csFile.GetLength();if(!bRet){TRACE("Open failed exception\r\n"); }if(dwFileLen > constIFileMaxLen){csFile.Seek(-constIFileMaxLen,CFile::end);char *pcBuf = new char[constIFileMaxLen];memset(pcBuf,0,constIFileMaxLen);csFile.Read(pcBuf,constIFileMaxLen);int iLoop = 0;for( iLoop = 0;iLoop<constIFileMaxLen;iLoop++){if(0x0a == pcBuf[iLoop]){break; }}iLoop++;csFile.SeekToBegin();csFile.Write(pcBuf+iLoop,constIFileMaxLen-iLoop);csFile.SetLength((DWORD)constIFileMaxLen-iLoop);delete [] pcBuf;pcBuf = NULL;}csFile.Flush();csFile.Close();}catch (...){csFile.Close();TRACE("Write log exception\r\n"); }
}
void CController::LogWriteOneRecord(CString strFunction,CString strType,CString strText)
{CDuplicatefilesclearDlg *pDlg = (CDuplicatefilesclearDlg*)m_pDlg;//LogWriteRecord("["+ CTime::GetCurrentTime().Format("%Y-%m-%d %H:%M:%S")+"]"+strText,GetLogFileName());TRACE(strText);TRACE("\r\n");m_strWriteText=("["+ CTime::GetCurrentTime().Format("%Y-%m-%d %H:%M:%S")+"]"+strFunction+"() "+strType+strText);LogWriteRecord(m_strWriteText,GetLogFileName());//显示到界面pDlg->AppendLog(strText);}
2,实现记录到UI Edit控件
2.1使用Edit控件,使用多行模式
2.2 编写ApendLog UI函数
void CDuplicatefilesclearDlg::AppendLog(CString str)
{CString strText;GetDlgItemText(IDC_EDIT_Msg,strText);strText += "\r\n";strText += str;if(strText.GetLength() > 10240){strText= strText.Right(strText.GetLength()/2);}SetDlgItemText(IDC_EDIT_Msg,strText);int nLen = ((CEdit*)GetDlgItem(IDC_EDIT_Msg))->SendMessage(WM_GETTEXTLENGTH);((CEdit*)GetDlgItem(IDC_EDIT_Msg))->SetSel(nLen, nLen, FALSE);
}
2.3 使用代码
m_pControl = new CController(this);m_pControl->LogWriteOneRecord("CDuplicatefilesclearDlg::OnInitDialog()","[I] "," CDuplicatefilesclearDlg::OnInitDialog()函数...");
2.5运行结果
完整代码上传到资源,欢迎下载!