Welcome 微信登录
编程资源 图片资源库 蚂蚁家优选 PDF转换器

首页 / 操作系统 / Linux / C++版的循环缓冲区类

C++版的循环缓冲区类(实际测试可用!)/*
 * CCycleBuffer.h
 *
 *  Created on: 2013-5-27
 *      Author: shiguang
 */#ifndef __test__CCycleBuffer__
#define __test__CCycleBuffer__
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
class CCycleBuffer
{
public:
 bool isFull();
 bool isEmpty();
 void Empty();
 int GetLength();
 CCycleBuffer(int size);
 virtual ~CCycleBuffer();
 int Write(char* buf, int count);
 int Read(char* buf, int count);
private:
 bool m_bEmpty, m_bFull;
 char * m_pBuf;
 int m_nBufSize;
 int m_nReadPos;
 int m_nWritePos;public:
 int GetReadPos()
 {
  return m_nReadPos;
 }
 int GetWritePos()
 {
  return m_nWritePos;
 }
};
#endif /* defined(__test__CCycleBuffer__) */ /*
 * main.cpp
 *
 *  Created on: 2013-5-27
 *      Author: shiguang
 */#include "CCycleBuffer.h"int main()
{
 CCycleBuffer buffer(100);
 char* datachar = new char[40];
 char* reschar = new char[100]; int res = 0; for (int i = 0; i < 40; ++i)
 {
  datachar[i] = i + 1;
 }
 res = buffer.Write(datachar, 40);
 printf("写入数据个数:%d ", res);
 res = buffer.Write(datachar, 40);
 printf("写入数据个数:%d ", res);
 res = buffer.Write(datachar, 40);
 printf("写入数据个数:%d ", res);
 res = buffer.Write(datachar, 40);
 printf("写入数据个数:%d ", res); res = buffer.Read(reschar, 100);
 printf("读取数据个数:%d ", res);
 for (int i = 0; i < 100; ++i)
 {
  if (i % 10 == 0)
  {
   printf(" ");
  }
  printf("%2d ", reschar[i]);
 } return 0;
}输出结果:写入数据个数:40
写入数据个数:40
写入数据个数:20
写入数据个数:0
读取数据个数:100 1    2    3    4    5    6    7    8    9 10 
11 12 13 14 15 16 17 18 19 20 
21 22 23 24 25 26 27 28 29 30 
31 32 33 34 35 36 37 38 39 40 
 1    2    3    4    5    6    7    8    9 10 
11 12 13 14 15 16 17 18 19 20 
21 22 23 24 25 26 27 28 29 30 
31 32 33 34 35 36 37 38 39 40 
 1    2    3    4    5    6    7    8    9 10 
11 12 13 14 15 16 17 18 19 20  源程序来自网络资料!