• MFC写日志功能,支持中文


    这是一个Unicode环境下支持中文的 txt 文件

    每一个小时生成一个新的文件,以 “年月日时” 命名

    每一条数据占一行,每一条数据前跟 “年月日时分秒” 标签

    速度可达到每秒300条左右

    //得到exe的根路径  所有的路径函数返回值最后都包括"\\"
    CString GetExeRootPath()
    {
        CString strModule;
        HMODULE hmod = GetModuleHandle(NULL);//获取一个应用程序或动态链接库的模块句柄。只有在当前进程的场景中,这个句柄才会有效。
        GetModuleFileName(hmod, strModule.GetBuffer(MAX_PATH), MAX_PATH);//MAX_PATH是C语言运行时库中通过#define指令定义的一个宏常量,它定义了编译器所支持的最长全路径名的长度。
        strModule.ReleaseBuffer();//在使用GetBuffer后使用
    
        CString strModulePath;
        int nPos = strModule.ReverseFind(_T('\\'));
        strModulePath = strModule.Left(nPos + 1);
    
        return strModulePath;
    }
    void CMFCApplication4Dlg::WriteDataToLogFile(CString strData)
    {
        CTime mTime;
        mTime = CTime::GetCurrentTime();
        CString strFileName;
        strFileName.Format(_T("%04d-%02d-%02d-%02d.log"), mTime.GetYear(), mTime.GetMonth(), mTime.GetDay(), mTime.GetHour());
        CString strPath;
        strPath = GetExeRootPath();
        strPath = strPath + _T("Data\\log\\") + strFileName;
    
        setlocale(LC_CTYPE, ("chs"));
        CStdioFile file;
        CFileException e;
        CString strErr;
        if (file.Open(strPath, CFile::modeCreate | CFile::modeNoTruncate | CFile::shareDenyNone | CFile::modeWrite | CFile::typeText, &e) == 0)
        {
            AfxMessageBox(_T("打开") + strPath + _T("文件失败"));
            strErr.Format(_T("错误代码:%d"), e.m_cause);
            AfxMessageBox(strErr);
            return;
        }
        file.SeekToEnd();
        CString strTime;
        strTime.Format(_T("[%04d-%02d-%02d %02d:%02d:%02d]"), mTime.GetYear(), mTime.GetMonth(), mTime.GetDay(), mTime.GetHour(), mTime.GetMinute(), mTime.GetSecond());
        strData = strTime + strData + _T("\n");
        file.WriteString(strData);
        file.Close();
    }

    关键点在于  CFile::shareDenyNone,否则打开失败可能性大增,错误代码:11  CFileException::sharingViolation 未加载SHARE.EXE或共享区被锁

  • 相关阅读:
    codeforces 1215 E Marbles-----状压DP
    留坑待填
    Catalan数
    砝码称重
    约数和
    硬币题解
    迎春舞会之数字舞蹈
    过剩数
    猜测棋局
    [NOIP普及组2014第三题]螺旋矩阵
  • 原文地址:https://www.cnblogs.com/ckrgd/p/15878472.html
Copyright © 2020-2023  润新知