用C语言 写一个环形buffer
时间: 2023-08-14 16:04:54 浏览: 160
下面是一个简单的环形缓冲区实现,使用C语言编写:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
char *data;
int head;
int tail;
int size;
} CircularBuffer;
CircularBuffer* createCircularBuffer(int size) {
CircularBuffer *buffer = (CircularBuffer*)malloc(sizeof(CircularBuffer));
buffer->data = (char*)malloc(sizeof(char) * size);
buffer->head = 0;
buffer->tail = 0;
buffer->size = size;
return buffer;
}
void destroyCircularBuffer(CircularBuffer *buffer) {
free(buffer->data);
free(buffer);
}
int isEmpty(CircularBuffer *buffer) {
return buffer->head == buffer->tail;
}
int isFull(CircularBuffer *buffer) {
return (buffer->tail + 1) % buffer->size == buffer->head;
}
int write(CircularBuffer *buffer, char *data, int len) {
if (isFull(buffer)) {
return 0;
}
int i;
for (i=0; i<len; i++) {
buffer->data[buffer->tail] = data[i];
buffer->tail = (buffer->tail + 1) % buffer->size;
}
return len;
}
int read(CircularBuffer *buffer, char *data, int len) {
if (isEmpty(buffer)) {
return 0;
}
int i;
for (i=0; i<len; i++) {
data[i] = buffer->data[buffer->head];
buffer->head = (buffer->head + 1) % buffer->size;
if (buffer->head == buffer->tail) {
break;
}
}
return i;
}
int main() {
CircularBuffer *buffer = createCircularBuffer(10);
char *data1 = "hello";
char *data2 = "world";
char *data3 = "this is a test";
write(buffer, data1, strlen(data1));
write(buffer, data2, strlen(data2));
write(buffer, data3, strlen(data3));
char read_data[20];
int len = read(buffer, read_data, 20);
read_data[len] = '\0';
printf("%s\n", read_data);
destroyCircularBuffer(buffer);
return 0;
}
```
这个实现中,我们使用一个结构体来表示环形缓冲区,其中包括一个指针、头和尾指针、缓冲区大小等信息。为了实现环形缓冲区,我们使用了取模运算来计算下一个指针的位置。在 `write` 函数中,我们将数据写入缓冲区的尾部;在 `read` 函数中,我们从缓冲区的头部读取数据。在 `main` 函数中,我们展示了如何使用这个环形缓冲区来写入和读取数据。
需要注意的是,在使用环形缓冲区时需要考虑读写指针的同步问题,避免数据的丢失或覆盖。
阅读全文