stdafx.cpp 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. // stdafx.cpp : 只包括标准包含文件的源文件
  2. // Test.pch 将作为预编译头
  3. // stdafx.obj 将包含预编译类型信息
  4. #include "stdafx.h"
  5. void writelog(const TCHAR *format, ...)
  6. {
  7. try
  8. {
  9. // 解析出日志路径;
  10. static TCHAR szlogpath[MAX_PATH] = {0};
  11. if ( szlogpath[0] == _T('\0') )
  12. {
  13. TCHAR szDrive[_MAX_DRIVE] = { 0 };
  14. TCHAR szDir[_MAX_DIR] = { 0 };
  15. TCHAR szFna[_MAX_DIR] = { 0 };
  16. TCHAR szExt[_MAX_DIR] = { 0 };
  17. TCHAR szModulePath[MAX_PATH] = {0};
  18. ::GetModuleFileName(NULL, szModulePath, sizeof(szModulePath) / sizeof(TCHAR));
  19. _tsplitpath_s(szModulePath, szDrive, szDir, szFna, szExt);
  20. _tcscpy_s(szModulePath, szDrive);
  21. _tcscat_s(szModulePath, szDir);
  22. _stprintf_s(szlogpath, _T("%s日志\\%s.txt"), szModulePath, szFna);
  23. }
  24. // 打开或创建文件;
  25. CStdioFile fp;
  26. if (PathFileExists(szlogpath))
  27. {
  28. if (fp.Open(szlogpath, CFile::modeWrite) == FALSE)
  29. {
  30. return;
  31. }
  32. ULONGLONG length = fp.GetLength();
  33. if (length > 10 * 1024 * 1024) // 10M;
  34. {
  35. fp.Close();
  36. ::DeleteFile(szlogpath);
  37. return;
  38. }
  39. fp.SeekToEnd();
  40. }
  41. else
  42. {
  43. fp.Open(szlogpath, CFile::modeCreate | CFile::modeWrite);
  44. }
  45. // 格式化前设置语言区域;
  46. TCHAR* old_locale = _tcsdup(_tsetlocale(LC_CTYPE, NULL));
  47. _tsetlocale(LC_CTYPE, _T("chs"));//设定中文;
  48. // 格式化日志内容;
  49. va_list args = NULL;
  50. int len = 0;
  51. TCHAR *buffer = NULL;
  52. va_start( args, format );
  53. // _vscprintf doesn't count. terminating '\0'
  54. len = _vsctprintf( format, args ) + 1;
  55. buffer = (TCHAR*)malloc( len * sizeof(TCHAR) );
  56. _vstprintf_s( buffer, len, format, args ); // C4996
  57. // Note: vsprintf is deprecated; consider using vsprintf_s instead
  58. // 将日志内容输入到文件中;
  59. fp.WriteString( CTime::GetCurrentTime().Format(_T("%Y-%m-%d %H:%M:%S ")) );
  60. fp.WriteString(buffer);
  61. fp.WriteString(_T("\n"));
  62. // 关闭文件,释放资源并设置回原语言区域;
  63. free( buffer );
  64. _tsetlocale(LC_CTYPE, old_locale);
  65. free(old_locale);//还原区域设定;
  66. fp.Close();
  67. }
  68. catch (CException *e)
  69. {
  70. e->ReportError();
  71. e->Delete();
  72. }
  73. }