手机版
你好,游客 登录 注册
背景:
阅读新闻

C++版的循环缓冲区类

[日期:2014-03-16] 来源:Linux社区  作者:sg131971 [字体:大 中 小]

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\n", res);
 res = buffer.Write(datachar, 40);
 printf("写入数据个数:%d\n", res);
 res = buffer.Write(datachar, 40);
 printf("写入数据个数:%d\n", res);
 res = buffer.Write(datachar, 40);
 printf("写入数据个数:%d\n", res);

 res = buffer.Read(reschar, 100);
 printf("读取数据个数:%d\n", res);
 for (int i = 0; i < 100; ++i)
 {
  if (i % 10 == 0)
  {
   printf("\n");
  }
  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 

源程序来自网络资料!

linux
相关资讯       C++  C语言缓冲区 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款