// stdafx.cpp : 只包括标准包含文件的源文件 // Test.pch 将作为预编译头 // stdafx.obj 将包含预编译类型信息 #include "stdafx.h" void writelog(const TCHAR *format, ...) { try { // 解析出日志路径; static TCHAR szlogpath[MAX_PATH] = {0}; if ( szlogpath[0] == _T('\0') ) { TCHAR szDrive[_MAX_DRIVE] = { 0 }; TCHAR szDir[_MAX_DIR] = { 0 }; TCHAR szFna[_MAX_DIR] = { 0 }; TCHAR szExt[_MAX_DIR] = { 0 }; TCHAR szModulePath[MAX_PATH] = {0}; ::GetModuleFileName(NULL, szModulePath, sizeof(szModulePath) / sizeof(TCHAR)); _tsplitpath_s(szModulePath, szDrive, szDir, szFna, szExt); _tcscpy_s(szModulePath, szDrive); _tcscat_s(szModulePath, szDir); _stprintf_s(szlogpath, _T("%s日志\\%s.txt"), szModulePath, szFna); } // 打开或创建文件; CStdioFile fp; if (PathFileExists(szlogpath)) { if (fp.Open(szlogpath, CFile::modeWrite) == FALSE) { return; } ULONGLONG length = fp.GetLength(); if (length > 10 * 1024 * 1024) // 10M; { fp.Close(); ::DeleteFile(szlogpath); return; } fp.SeekToEnd(); } else { fp.Open(szlogpath, CFile::modeCreate | CFile::modeWrite); } // 格式化前设置语言区域; TCHAR* old_locale = _tcsdup(_tsetlocale(LC_CTYPE, NULL)); _tsetlocale(LC_CTYPE, _T("chs"));//设定中文; // 格式化日志内容; va_list args = NULL; int len = 0; TCHAR *buffer = NULL; va_start( args, format ); // _vscprintf doesn't count. terminating '\0' len = _vsctprintf( format, args ) + 1; buffer = (TCHAR*)malloc( len * sizeof(TCHAR) ); _vstprintf_s( buffer, len, format, args ); // C4996 // Note: vsprintf is deprecated; consider using vsprintf_s instead // 将日志内容输入到文件中; fp.WriteString( CTime::GetCurrentTime().Format(_T("%Y-%m-%d %H:%M:%S ")) ); fp.WriteString(buffer); fp.WriteString(_T("\n")); // 关闭文件,释放资源并设置回原语言区域; free( buffer ); _tsetlocale(LC_CTYPE, old_locale); free(old_locale);//还原区域设定; fp.Close(); } catch (CException *e) { e->ReportError(); e->Delete(); } }