环形缓存滑窗加c语言代码
时间: 2023-11-08 11:05:22 浏览: 71
C 语言中实现环形缓冲区
环形缓存滑窗是一种常见的数据缓存方式,它可以在固定大小的缓冲区中存储数据,并且可以循环使用。当添加数据时,head指针前进;当使用数据时,tail指针向前移动。当到达缓冲区的尾部时,指针又回到缓冲区的起始位置。这种方式可以有效地解决在C语言编程场景中需要对一段不定长数据进行缓存的问题。
以下是一个基于数组的环形缓冲队列的C语言代码示例:
```
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#define BUFFER_SIZE 5
typedef unsigned char UINT8;
typedef unsigned int UINT32;
UINT8 buffer[BUFFER_SIZE] = {0};
UINT32 head = 0;
UINT32 tail = 0;
void writeRingbuffer(UINT8 *data, UINT32 len)
{
UINT32 i;
for(i = 0; i < len; i++)
{
buffer[head] = data[i];
head = (head + 1) % BUFFER_SIZE;
if(head == tail)
{
tail = (tail + 1) % BUFFER_SIZE;
}
}
}
UINT32 readRingbuffer(UINT8 *data, UINT32 len)
{
UINT32 i;
UINT32 readLen = 0;
for(i = 0; i < len; i++)
{
if(head == tail)
{
break;
}
data[i] = buffer[tail];
tail = (tail + 1) % BUFFER_SIZE;
readLen++;
}
return readLen;
}
void releaseRingbuffer()
{
head = 0;
tail = 0;
}
int main()
{
UINT8 c;
UINT32 readLen,i;
UINT8 readBuffer[5] = {0};
printf("Please enter a line>\n");
do{
c = getchar();
putchar(c);
switch(c)
{
case 'Q':
goto exit;
break;
case 'R':
readLen = readRingbuffer(readBuffer,5);
printf("readRingbuffer len:%d\n",readLen);
if(readLen > 0)
{
printf("readRingbuffer:");
for(i = 0; i < readLen; i++)
{
printf("%c ",(UINT8)readBuffer[i]);
}
printf("\n");
}
break;
default :
if(c != '\n')
writeRingbuffer((UINT8*)&c,1);
break;
}
}while(1);
exit:
releaseRingbuffer();
printf("\nexit!\n");
return 0;
}
```
阅读全文