C++ 日志

简单日志


#include <fstream>

ofstream fLog;

int len;

fLog.open("d:\\log.txt",ios::app);

if(fLog.good())
{
fLog<<"XXXXXXX"<<endl;
fLog<<len<<endl;
char* str1=new char[len *2+2];
fLog<<str1<<endl;
if (str1 !=NULL)
{
delete [] str1;
str1 =NULL;
}
}

fLog.close();


日志类

#pragma once
#include <fstream>//头文件要加个h
#include <stdio.h>//头文件要加个h

using namespace std;

class CLog
{
protected:
	CLog()
		: _write(false) {};

public:
	~CLog();

	static CLog* ins() 
        {
		return &_instance;
	};

	void Load(const char* log_name);
	void LogOn(bool write);
	void Write(const char* log, bool force=false);
	void Write(int log, int width, bool force=false);
	void Write(const BYTE* log, int len, bool force=false);
	void Close();

protected:
	static CLog _instance;
	ofstream _log_file;//vc6的ofstream非标准,不要std的,坑爹啊
	bool _write;
	FILE *stream_;
};
源文件


#include "StdAfx.h"
#include "log.h"
#include <iomanip>
#include <locale.h>

CLog CLog::_instance;

CLog::~CLog() {
	if (_log_file.is_open())
		_log_file.close();
}

void CLog::LogOn(bool write) {
	_write = write;
}

void CLog::Load(const char* log_name)
      {
	stream_ = fopen(log_name, "wt");
	return;
       }


void CLog::Write(const char* log, bool force) {
	if (!_write && !force)
		return;
	fwrite(log, sizeof(char), strlen(log), stream_);
	fwrite("\n", sizeof(char), 1, stream_);
	return;
}

void CLog::Write(int log, int width, bool force) {
	if (!_write && !force)
		return;
	char buff[20];
	sprintf(buff, "%0*X", width, log);
	fwrite(buff, sizeof(char), strlen(buff), stream_);
	fwrite("\n", sizeof(char), 1, stream_);
	return;
}

void CLog::Write(const BYTE* log, int len, bool force) {
	if (!_write && !force)
		return;

	char buff[3];
	for (int i = 0; i< len; ++i) {
		sprintf(buff, "%02X", log[i]);
		fwrite(buff, sizeof(char), 2, stream_);
	}
	fwrite("\n", sizeof(char), 1, stream_);
	return;
}

void CLog::Close() {
	if (!_write)
		return;
	
	fclose(stream_);
	return;
}


VC6 和其他版本包含头文件不一致,需区分

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值