C语言实现队循FIFO缓冲区-《30天自制操作系统》

192 篇文章 4 订阅 ¥19.90 ¥99.00
本文详细介绍了如何使用C语言实现一个基于字符的循环FIFO缓冲区,包括初始化、数据写入、数据读取和状态查询等功能。通过提供的fifo8.h头文件和源代码,展示了FIFO缓冲区的数据结构和操作函数,如fifo8_init、fifo8_put、fifo8_get等,同时也添加了fifo8_free函数以检查剩余容量。
摘要由CSDN通过智能技术生成

本代码整理自《30天自制操作系统》P135的整理FIFO缓冲区

写的很好,所以记录一下(增加了一个fifo8_free函数,用于查询剩余容量,觉得有用)。作者实现的是char类型的缓冲区,但是可以用你要传的任意结构体来替换~~~

fifo8.h

[html]  view plain  copy
  1. /*溢出标志:0-正常,-1-溢出*/  
  2. #define FLAGS_OVERRUN 0x0001  
  3. /*  
  4.         buf- 缓冲区地址  
  5.         size- 大小  
  6.         free- 空余容量  
  7.         putP- 下一个数据写入位置  
  8.         getP- 下一个数据独处位置  
  9. */  
  10. struct FIFO8{  
  11.          unsigned char *buf;  
  12.          int putP,getP,size,free,flags;  
  13. };  
  14.   
  15. void fifo8_init(struct FIFO8 *fifo,int size, unsigned char *buf);  
  16. int fifo8_put(struct FIFO8 *fifo,unsigned char data);  
  17. int fifo8_get(struct FIFO8 *fifo);  
  18. int fifo8_status(struct FIFO8 *fifo);  
  19. int fifo8_free(struct FIFO7 *fifo);  
fifo8.c
[html]  view plain  copy
  1. #include "fifo8.h"  
  2. void fifo8_init(struct FIFO8 *fifo,int size, unsigned char *buf)  
  3. /*初始化*/  
  4. {  
  5.         fifo->buf=buf;  
  6.         fifo->flags=0;            
  7.         fifo->free=size;  
  8.         fifo->size=size;  
  9.         fifo->putP=0;                     
  10.         fifo->getP=0;                     
  11.   
  12.          return;  
  13. }  
  14. int fifo8_putPut(struct FIFO8 *fifo,unsigned char data)  
  15. /*向FIFO 中写入数据 */  
  16. {  
  17.          if(fifo->free==0){  
  18.                 fifo->flags |= FLAGS_OVERRUN;  
  19.                  return -1;  
  20.         }  
  21.         fifo->buf[fifo->putP] = data;  
  22.         fifo->putP++;  
  23.          //循环队列缓冲区  
  24.          if(fifo->putP == fifo->size){  
  25.                 fifo->putP = 0;  
  26.         }  
  27.         fifo->free--;  
  28.   
  29.          return 0;  
  30. }  
  31. int fifo8_get(struct FIFO8 *fifo)  
  32. /*从FIFO 中取出一个数据 */  
  33. {  
  34.          int data;  
  35.          if(fifo->free == fifo->size){  
  36.                  return -1;  
  37.         }  
  38.         data = fifo->getP;  
  39.         fifo->getP++;  
  40.          if(fifo->getP == fifo->size){//用来实现循环  
  41.                 fifo->getP = 0;  
  42.         }  
  43.         fifo->free++;  
  44.           
  45.          return data;  
  46. }  
  47. int fifo8_status(struct FIFO8 *fifo)  
  48. /*缓冲区被使用容量*/  
  49. {  
  50.          return fifo->size-fifo->free;  
  51. }  
  52. int fifo8_free(struct FIFO8 *fifo)  
  53. /*缓冲区剩余容量*/  
  54. {  
  55.          return fifo->free;  
  56. }  

http://blog.csdn.net/fovwin/article/details/8129102
学习的地方:返回值为void时可以return;循环缓冲区的构造;溢出标志设定;
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值