#include<stdio.h>
#include<stdlib.h>
typedef struct {
char * buf;
int head;
int tail;
int size;
} fifo_t;
//This initializes the FIFO structure with the given buffer and size
void fifo_init(fifo_t * f, char * buf, int size){
f->head = 0;
f->tail = 0;
f->size = size;
f->buf = buf;
}
//This reads nbytes bytes from the FIFO
//The number of bytes read is returned
int fifo_read(fifo_t * f, void * buf, int nbytes){
int i;
char * p;
p = buf;
for(i=0; i < nbytes; i++){
if( f->tail != f->head ){ //see if any data is available
*p++ = f->buf[f->tail]; //grab a byte from the buffer
f->tail++; //increment the tail
if( f->tail == f->size ){ //check for wrap-around
f->tail = 0;
}
} else {
return i; //number of bytes read
}
}
return nbytes;
}
//This writes up to nbytes bytes to the FIFO
//If the head runs in to the tail, not all bytes are written
//The number of bytes written is returned
int fifo_write(fifo_t * f, const void * buf, int nbytes){
int i;
const char * p;
p = buf;
for(i=0; i < nbytes; i++){
//first check to see if there is space in the buffer
if( (f->head + 1 == f->tail) || ( (f->head+1 == f->size) && (f->tail == 0) )){
return i; //no more room
} else {
f->buf[f->head] = *p++;
f->head++; //increment the head
if( (f->head == f->size)){ //check for wrap-around
f->head = 0;
}
}
}
return nbytes;
}
int main(){
fifo_t f;
char wr_buffer[10]={'a','n','v','s','d'};
char rd_buffer[10];
char * fifo_buffer;
int size, nb_wr, nb_rd, i;
printf("donner la taille du buffer :\n");
scanf("%d",&size);
fifo_buffer = malloc(size * sizeof(char));
fifo_init(&f, fifo_buffer, size);
nb_wr = fifo_write(&f, wr_buffer, 4);
nb_rd = fifo_read(&f, rd_buffer, 6);
printf("\n nombre de trames ecrites : \t %d \n",nb_wr);
for(i=0;i<nb_wr;i++){
printf("\t - trame %d : %c \n", i, f.buf[i]);
}
printf("\n nombre de trames lues : \t %d \n",nb_rd);
for(i=0;i<nb_rd;i++){
printf("\t - trame %d : %c \n", i, rd_buffer[i]);
}
}
小波思基
- 粉丝: 85
- 资源: 1万+
最新资源
- Python MIDI 库.zip
- Python for DevOps repo 包含有用的 Python 脚本,可供您学习并在日常 DevOps 自动化任务中实施 .zip
- Python API 包装器和库列表.zip
- Python - 与我的 YouTube 频道相关的脚本存储在这里,可以用任何版本的 Python 编写.zip
- PyClass 课程计划.zip
- Puppet 模块用于安装和管理 Python、pip、virtualenvs 和 Gunicorn 虚拟主机 .zip
- jieshao123456
- Java 将本地mp4推流rtsp
- 第7章 聚类算法 - 作业 - 副本.ipynb
- Gartner发布2024年中国网络安全发展趋势
资源上传下载、课程学习等过程中有任何疑问或建议,欢迎提出宝贵意见哦~我们会及时处理!
点击此处反馈