#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]);
}
}