论坛首页 编程语言技术论坛

C++ 记录日志类

浏览 3962 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (4) :: 隐藏帖 (0)
作者 正文
   发表时间:2010-10-11  
C++

 今天,修改了以前的读写IC卡Activex组件,对于组件添加了记录日志类。

 // LogManager.h: interface for the LogManager class.

//
//////////////////////////////////////////////////////////////////////

#if !defined(AFX_LOGMANAGER_H__0A40E9CA_BE55_427D_ADE9_C16E706B3430__INCLUDED_)
#define AFX_LOGMANAGER_H__0A40E9CA_BE55_427D_ADE9_C16E706B3430__INCLUDED_

#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include<ctime>

class LogManager  
{
public:
	LogManager();
	virtual ~LogManager();
public:
	void WriteLog(TCHAR* logs);
};

#endif // !defined(AFX_LOGMANAGER_H__0A40E9CA_BE55_427D_ADE9_C16E706B3430__INCLUDED_)

 

 // LogManager.cpp: implementation of the LogManager class.

//
//////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include "LogManager.h"
#define BUFSIZE 4096
#define DATELEN 64 
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

LogManager::LogManager()
{

}

LogManager::~LogManager()
{

}

void LogManager::WriteLog(TCHAR* logs)
{

	CHAR sBuff[BUFSIZE];
	CHAR sPathBuff[MAX_PATH];//日志文件路径
	CHAR* p;
	CHAR date[DATELEN]; //日期
	CHAR* CARD_FILE_FLAG = "CFCC_CARD_FILE_";
	CHAR* CARD_FILE_EXTENDS_FLAG = ".log";
	//-------------获取临时文件路径----------------
	time_t t = time(0); 
	strftime(date,9, "%Y%m%d",localtime(&t));
	// Get the temp path
	GetTempPath(MAX_PATH,   // length of the buffer
		sPathBuff);      // buffer for path 
	int icurrPathLen = strlen(sPathBuff);
	int ifileFlagLen = strlen(CARD_FILE_FLAG);
	int ifileExtendsLen = strlen(CARD_FILE_EXTENDS_FLAG);
	p = &sPathBuff[icurrPathLen];
	memcpy(p,CARD_FILE_FLAG,ifileFlagLen);
	p = p + ifileFlagLen;
	memcpy(p,date,8);
	p = p + 8;
	memcpy(p,CARD_FILE_EXTENDS_FLAG,ifileExtendsLen + 1);
	//---------------写日志---------------------------
	HANDLE hFile = CreateFile(sPathBuff, GENERIC_READ|GENERIC_WRITE, 
		FILE_SHARE_READ | FILE_SHARE_WRITE,
		NULL,
		OPEN_ALWAYS, 
		0, 
		0);		
	if (hFile != INVALID_HANDLE_VALUE)
	{
		LONG lDistance = 0;
		DWORD nReads = 0;
		SetFilePointer(hFile,lDistance,NULL,FILE_END);
		//begin write log
		//write date
		time_t currentT = time(0); 
		strftime(date,sizeof(date), "%c---",localtime(&t));
		WriteFile(hFile,date,strlen(date),&nReads,NULL);
		//write log
		strcpy(sBuff,logs);
		WriteFile(hFile,sBuff,strlen(logs),&nReads,NULL);
		WriteFile(hFile,"\r\n",2,&nReads,NULL);//回车换行
		
		FlushFileBuffers(hFile);
		CloseHandle(hFile); 
	}
}
 
   发表时间:2010-11-30  
似乎单例+静态方法比较好。
0 请登录后投票
论坛首页 编程语言技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics