//
//log.h head file
// //write log file //protected member function //private member function // #pragma once class CLog { protected: CLog(void); ~CLog(void); public: static void Init(CLog* &plog); void Log(const char* lpMsg,const char* lpFile = NULL); private: void WriteLog(const char* lpMsg,const char* lpFile = NULL); };
// //log.cpp // #include "StdAfx.h" #include "Log.h" CLog::CLog(void) { } CLog::~CLog(void) { } void CLog::WriteLog(const char* lpMsg,const char* lpFile) { char lpFileName[256] = "\0"; if (!lpFile){ strcpy(lpFileName,"D:\\Log\\test\\log.txt"); } else{ strcpy(lpFileName,lpFile); } FILE* pFile = fopen(lpFileName,"r"); if (!pFile){ pFile = fopen(lpFileName,"w");//create file if not exist fputs(lpMsg,pFile); fclose(pFile); } else{ fclose(pFile); pFile = fopen(lpFileName,"a");// add if file exist fputs(lpMsg,pFile); fclose(pFile); } } void CLog::Init( CLog* &plog ) { if (!plog){ plog = new CLog(); } } void CLog::Log(const char* lpMsg,const char* lpFile) { WriteLog(lpMsg,lpFile); }
// //other cpp file // #include "Log.h" CLog* g_plog = NULL; void COperateFile::Tick() { LARGE_INTEGER litmp; LONGLONG Qpart1,Qpart2; double dMinus,dFreq,dTime; QueryPerformanceFrequency(&litmp); dFreq = (double)litmp.QuadPart; QueryPerformanceCounter(&litmp); Qpart1 = litmp.QuadPart; //do something Sleep(1567); QueryPerformanceCounter(&litmp); Qpart2 = litmp.QuadPart; dMinus = (double)(Qpart2-Qpart1); dTime = dMinus/dFreq *1000; //ms,microSecond ///dTime = dMinus/dFreq //s,second char lpSpendTime[256] = "\0"; sprintf(lpSpendTime," Cost Time: %lf ms %d NO",dTime,nCount++); //get system time SYSTEMTIME systemTime; memset((void*)&systemTime,0,sizeof(SYSTEMTIME)); GetSystemTime(&systemTime); char lpSystemTime[256] = "\0"; sprintf(lpSystemTime,"[ %4d.%2d.%2d %2d:%2d:%2d ]",systemTime.wYear,\ systemTime.wMonth,systemTime.wDay,systemTime.wHour+8,\ systemTime.wMinute,systemTime.wSecond); char lpMsg[512] = "\0"; strcpy(lpMsg,lpSystemTime); strcat(lpMsg,lpSpendTime); strcat(lpMsg,"\n"); //write message to txt file if (!g_plog){ CLog::Init(g_plog); } if (g_plog){ g_plog->Log(lpMsg); }
/*char lpFileName[256] = "\0"; strcpy(lpFileName,"D:\\Log\\test\\log.txt"); FILE* pFile = fopen(lpFileName,"r"); if (!pFile){ pFile = fopen(lpFileName,"w");//create file if not exist fputs(lpMsg,pFile); fclose(pFile); } else{ fclose(pFile); pFile = fopen(lpFileName,"a");// add if file exist fputs(lpMsg,pFile); fclose(pFile); } */ }