快没电了,先贴代码。稍后再写别的,代码写得比较简单,以后再支持其它功能吧!
#ifndef __CBUFFER_H__
#define __CBUFFER_H__
#include <stdio.h>
#include <string>
#include <iostream>
using namespace std;
class CBuffer
{
public:
CBuffer(const std::string filename, const std::string mode="r+",
const time_t timeval =60, size_t maxsize =1024);
virtual ~CBuffer();
int writeBuffer(char*, const size_t);
int writeFile();
protected:
private:
//文件名称
std::string m_filename;
//输出流句柄
FILE * m_fp;
//写入文件模式
std::string m_writemode;
//上次写文件时间
time_t m_lasttime;
//间隔时间
time_t m_intervaltime;
//缓冲最大长度
size_t m_maxsize;
//缓冲区指针
char * m_buffer;
//缓冲区末端位置
size_t m_pos;
};
#endif //endof __CBUFFER_H__
#include "CBuffer.h"
/**
* @desc Constructor
*/
CBuffer::CBuffer(const std::string filename, const std::string mode,
const time_t timeval, size_t maxsize)
:m_filename(filename),m_writemode(mode),
m_intervaltime(timeval),m_maxsize(maxsize)
{
if((NULL != m_fp) || m_filename.empty())
return;
m_fp = fopen(m_filename.c_str(), m_writemode.c_str());
m_buffer = new char[m_maxsize];
m_pos =0;
m_lasttime =0;
}
/**
* @desc Destructor
*/
CBuffer::~CBuffer()
{
delete m_buffer;
m_buffer = NULL;
if(m_pos != 0) writeFile();
fclose(m_fp);
}
/**
* @desc 获取格林尼治时间的具体秒数
*/
time_t getGMTSecond()
{
return time(0);
}
/**
* @desc 写入缓冲
*/
int CBuffer::writeBuffer(char* in_buf, const size_t len)
{
time_t second =getGMTSecond();
if(m_lasttime ==0) m_lasttime=second;
//缓冲满或者时间达到约定间隔
if((m_pos+len >= m_maxsize)
||m_lasttime+m_intervaltime > second){
int ret =writeFile();
if(ret < 0) return ret;
m_lasttime = second;
}
memcpy(m_buffer+m_pos, in_buf, len);
m_pos += len;
return 0;
}
/**
* @desc 写入文件
*/
int CBuffer::writeFile()
{
fwrite(m_buffer, 1, m_pos, m_fp);
fflush(m_fp);
//initionalize the buff;
memset(m_buffer,0,m_maxsize);
m_pos = 0;
return 0;
}
int main(int argc, const char * argv[])
{
char file_name[]="/Applications/code/CBuffer/log.dat";
CBuffer buf(file_name, "rw", 10, 1024);
char log[]="123458765454hfdsahjjjjjjjjjjjjkjkjkjkjkjkjkjkjkjkjhjjkkokokokokokokokokokokokokokoko"
"kokokokokokokokokokokokokokokokokokokokokokokokokokokokokokokokokokokokokokokokokokokokokok"
"okokokokokokokokokokokokookokokokokokookokhjhjhjhjhjhjhjhjhjhjhjhjhjhjhjhjhjhjhjhjhjhjhjhjh"
"jhjhjhjhjhjhjhjhjhjhjhjhhhhhhhhhhhhhhhhhhuuuuuuuu8989898989898989898989bvcdfgh";
for (int i=0; i<10000; i++) {
buf.writeBuffer(log, sizeof(log));
std::cout<<i;
if(i%500 == 300)
sleep(2);
}
return 0;
}