#include <stdio.h>
#include <stdlib.h>
#define RINGBUF_LEN 32
typedef struct ringbuf_t
{
int head;//头指针
int tail;//尾指针
int len;//长度
char buf[RINGBUF_LEN];//缓冲大小
}ringbuf_t;
ringbuf_t t_buf_ring;
//缓冲区初始化
void init_ringbuf(void)
{
memset(&t_buf_ring, 0, sizeof(t_buf_ring));
}
//入队
int ringbuf_write(char data)
{
if(RINGBUF_LEN <= t_buf_ring.len) {
return -1;
}
t_buf_ring.buf[t_buf_ring.tail] = data;
t_buf_ring.tail = (t_buf_ring.tail + 1) % RINGBUF_LEN;
t_buf_ring.len++;
return 0;
}
//出队
int ringbuf_read(char *date)
{
if(0 >= t_buf_ring.len) {
return -1;
}
*date = t_buf_ring.buf[t_buf_ring.head];
t_buf_ring.head = (t_buf_ring.head + 1) % RINGBUF_LEN;
t_buf_ring.len--;
return 0;
}
//出队
int ringbuf_show()
{
int i,j;
for (i = 0, j = t_buf_ring.head; i < t_buf_ring.len; i++, j++) {
printf("%d --- %c ", i, t_buf_ring.buf[j]);
}
printf("\n");
return 0;
}
// 主函数
int main()
{
char c, c_r;
int i, cnt;
//setvbuf(stdout,NULL,_IONBF,0); //pinrtf、putchar不能立马输出,打开此注释
//init_ringbuf();
printf("Please enter a line [blank line to terminate]> ");
do{
c=getchar();
putchar(c);
switch(c)
{
case 'Q':
goto exit;
break;
case 'R':
printf("----------read----------------\n");
printf("len - %d \n", t_buf_ring.len);
cnt = t_buf_ring.len;
for (i = 0; i < cnt; i++) {
ringbuf_read(&c_r);
printf("%d ---- %c ", i, c_r);
}
//ringbuf_show();
break;
default :
printf("----------write-----\n");
if(c!='\n')
ringbuf_write(c);
printf("%d len\n", t_buf_ring.len);
ringbuf_show();
break;
}
}while (1);
exit:
printf("exit.\n");
return 0;
}