首页 > C/C++ > C++写日志
2010
11-02

C++写日志

// writelog [11/2/2010 dnybz]

#include <fstream>
#include <time.h>

using namespace std;

#pragma warning(disable:4996)

/************************************************************************/
/*	功能: 写日志
/*	用法: writelog(filename,"this is a log test")
/************************************************************************/
bool writelog(char* filename,char* msg)
{
	time_t t;
	time(&t);
	struct tm *localt;
	localt = localtime(&t);

	char timebuf[128] = {0};

	sprintf(timebuf,
		"%4d-%02d-%02d %02d:%02d:%02d",
		localt->tm_year + 1900,
		localt->tm_mon + 1,
		localt->tm_mday,
		localt->tm_hour,
		localt->tm_min,
		localt->tm_sec);

	strcat(timebuf,"  ");
	strcat(timebuf,msg);

	ofstream LogFile;
	LogFile.open(filename,ios::app|ios::binary);
	LogFile.seekp(0,ios::end);

	if (LogFile.is_open())
	{
		/*Don't use sizeof(timebuf)*/
		LogFile.write(timebuf, strlen(timebuf));
		LogFile.write("\r\n", 2);
	}
	else
	{
		LogFile.close();
		return false;
	}
	LogFile.close();

	return true;
}

 

输出的日志文件是这样的

2010-11-02 17:52:17 this is a log test
2010-11-02 17:52:18 this is a log test

最后编辑:
作者:dnybz
这个作者貌似有点懒,什么都没有留下。