歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> C++版的循環緩沖區類

C++版的循環緩沖區類

日期:2017/3/1 9:47:11   编辑:Linux編程

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

源程序來自網絡資料!

Copyright © Linux教程網 All Rights Reserved