使用CFile生成log文件的方法

下面实例是在退出程序点击退出按钮时,在主程序的根目录下生成一个Log记录,用来记录程序的退出时间,具体实现代码与调试代码如下:

void CDebugDlg::OnClose()
{
 // TODO: 在此添加消息处理程序代码和/或调用默认值
 
 CFile file;
 CTime time=CTime::GetCurrentTime();

 CString str1="记录系统退出时间为:";
 CString str2=time.Format("%y-%m-%d %H:%M:%S");
 CString str3=" ";
 unsigned char pchData[MAX_PATH]={0};

 file.Open("Log.txt",CFile::modeCreate|CFile::modeNoTruncate|CFile::modeReadWrite);
 file.Read(pchData,MAX_PATH);

 if (MessageBox("你是否确定现在退出软件?","系统提示",MB_OKCANCEL|MB_ICONQUESTION)==IDOK)
 {
  
  str1+=str2;
  str1+=str3;
  MessageBox(str1,"提示一");
  file.Write(str1,str1.GetLength());
  MessageBox(str1+(char*)pchData,"提示二");  //打印当前缓冲区文件中的数据

  OnCancel();
 }

实例二:

相对实例一中的代码来说,只是在代码一的基础上,在log输出文件中增加了打印当前应用程序标题名,其中标题名由title变量变示,具体修改如下:

void CDebugDlg::OnClose()
{
 // TODO: 在此添加消息处理程序代码和/或调用默认值
 
 CFile file;
 CTime time=CTime::GetCurrentTime();

 CString str1="----系统退出时间为:";
 CString str2=time.Format("%y-%m-%d %H:%M:%S");
 CString str3=" ";
 CString title="";
 unsigned char pchData[MAX_PATH]={0};

 GetWindowText(title);  //获取应用程序标题名

 file.Open("Log.txt",CFile::modeCreate|CFile::modeNoTruncate|CFile::modeReadWrite);
 file.Read(pchData,MAX_PATH);

 if (MessageBox("你是否确定现在退出软件?","系统提示",MB_OKCANCEL|MB_ICONQUESTION)==IDOK)
 {
  title+=str1;
  title+=str2;
  title+=str3;
  MessageBox(title,"提示一");

  file.Write(title,title.GetLength());
  MessageBox(title+(char*)pchData,"提示二");  //打印当前缓冲区文件中的数据

  OnCancel();
 }
}

原文地址:https://www.cnblogs.com/jinjiangongzuoshi/p/3294552.html