写一个在单一线程下,不断的对一块缓冲进行读写的类,要求数据先进先出
#include "CT.h"
int main()
{
CAcesBuff * cb = CAcesBuff::getInstance();
cb->create(100);
unsigned char* bb = new unsigned char[12];
memcpy(bb,"abfsevf",12); //如果用strcat记得memset初始化bb'\0'
cb->write(bb,12);
unsigned char* buf = new unsigned char[100];
memset(buf,'\0',100);
cb->read(buf,13);
std::cout << buf1 << std::endl;
return 0;
}
#include "CT.h"
#include <exception>
//单例模式
CAcesBuff* CAcesBuff::m_Instance = new CAcesBuff;
char* CAcesBuff::m_Buf = nullptr;
CAcesBuff::CAcesBuff()
{
}
CAcesBuff::~CAcesBuff()
{
delete[] m_Buf;
}
CAcesBuff* CAcesBuff::getInstance()
{
if (m_Instance == nullptr)
{
m_Instance = new CAcesBuff;
}
return m_Instance;
}
bool CAcesBuff::create(int nBufSize)
{
bool bret = false;
if (m_Buf == nullptr)
{
m_nBufSize = nBufSize;
m_Buf = new char[nBufSize];
memset(m_Buf,'\0',nBufSize); //少了初始化
bret = true;
}
return bret;
}
int CAcesBuff::read(unsigned char* pbuf, int nSize)
{
//判断是否有值
if (!(*m_Buf))
{
cout << "没有值" << endl;
return 0;
}
int retLen = 0;
if(strncpy((char*)pbuf,m_Buf,nSize))
{
if (nSize >= strlen(m_Buf))
{
retLen = strlen(m_Buf);
memset(m_Buf,'\0',strlen(m_Buf));
}
else
{
char *tmp = new char[m_nBufSize];
memset(tmp,'\0',m_nBufSize);
strncpy(tmp,m_Buf+nSize,strlen(m_Buf)-nSize);
strcat(m_Buf,tmp);
delete[] tmp;
tmp = NULL;
retLen = nSize;
}
}
cout << "剪去后: " << m_Buf << endl;
return retLen;
}
int CAcesBuff::write(unsigned char*pbuf, int nSize)
{
//判断长度是否超了
if (strlen(m_Buf) + nSize > m_nBufSize)
{
cout << "写入长度超出了缓存长度:"<< m_Buf << ":: "<<strlen(m_Buf) <<"::" << nSize <<":" << m_nBufSize << endl;
return 0;
}
//mei超
try
{
if(strcat(m_Buf,(char*)pbuf))
return nSize;
}
catch (exception* e)
{
cout << e->what() << endl;
}
return 0;
}
#pragma one
#ifndef __CACES_BUFF_H__
#define __CACES_BUFF_H__
#include <iostream>
#include <vector>
using namespace std;
class CAcesBuff
{
CAcesBuff();
static CAcesBuff* m_Instance;
private:
static char* m_Buf;
int m_nBufSize;
public:
~CAcesBuff();
static CAcesBuff* getInstance();
/*说明: 创建数据缓冲
* 参数: nBufsize,指定的缓冲大小
* 返回值:成功为TRUE,失败为FALSE
*/
bool create(int nBufSize);
/*说明: 读取一定长度数据
* 参数: pBuf 存放读出数据缓冲
* nSize 要读出的数据长度
* 返回值:实际读取的数据长度
*/
int read(unsigned char* pbuf, int nSize);
/*说明: 写入一定长度数据
* 参数: pBuf 写入数据缓冲
* nSize 要写入的数据长度
* 返回值:实际写入的数据长度
*/
int write(unsigned char*pbuf, int nSize);
};
#define SINGLE_CACESBUFF CAcesBuff::getInstance()
#endif