Created
October 24, 2016 17:58
-
-
Save arthurafarias/a9827f8d34aebe32b984627e1f20599b to your computer and use it in GitHub Desktop.
A simple fifo demostration written in C
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* To compile this code just type in terminal | |
* gcc fifo.c -o fifo | |
* ./fifo | |
*/ | |
#include <stdio.h> | |
#include <stdlib.h> | |
char fifo[256]; | |
int fifo_tail; | |
int fifo_head; | |
int fifo_n_data; | |
#define FIFO_MAX 256; | |
int fifo_data_isavailable(); | |
int fifo_data_isfull(); | |
int fifo_push(char data); | |
char fifo_pull(void); | |
void | |
clear_stdin (void) | |
{ | |
while ( getchar() != '\n' ); | |
} | |
int main(void) | |
{ | |
char op; | |
char data; | |
while (1) | |
{ | |
printf("Entre com uma opção:\n1 - Insira um dado na fifo;\n2 - Recupere um dado da fifo.\n"); | |
op = getc(stdin); | |
clear_stdin(); | |
switch(op) | |
{ | |
case '1': | |
printf("Insira um caractere: "); | |
data = getc(stdin); | |
clear_stdin(); | |
if (!fifo_push(data)) | |
{ | |
printf("Falha ao inserir o dado.\n"); | |
} | |
else | |
printf("Dado inserido com sucesso.\n"); | |
break; | |
case '2': | |
if (fifo_data_isavailable()) | |
{ | |
printf("Dado: %c\n", fifo_pull()); | |
} | |
else | |
{ | |
printf("Nenhum dado disponível!\n"); | |
} | |
break; | |
default: | |
printf("Opção Inválida!\n"); | |
break; | |
} | |
} | |
return EXIT_SUCCESS; | |
} | |
int fifo_data_isavailable() | |
{ | |
if (fifo_n_data > 0) | |
{ | |
return 1; | |
} | |
else | |
{ | |
return 0; | |
} | |
} | |
int fifo_data_isfull() | |
{ | |
if (fifo_n_data < 256) | |
return 0; | |
else | |
return 1; | |
} | |
int fifo_push(char data) | |
{ | |
if (!fifo_data_isfull()) | |
{ | |
fifo[fifo_head] = data; | |
if (fifo_head < 255) | |
{ | |
fifo_head ++; | |
} | |
else | |
{ | |
fifo_head = 0; | |
} | |
fifo_n_data ++; | |
return 1; | |
} | |
else | |
{ | |
return 0; | |
} | |
} | |
char fifo_pull(void) | |
{ | |
char data; | |
if(fifo_data_isavailable()) | |
{ | |
data = fifo[fifo_tail]; | |
if (fifo_tail < 255) | |
{ | |
fifo_tail ++; | |
} | |
else | |
{ | |
fifo_tail = 0; | |
} | |
fifo_n_data --; | |
return data; | |
} | |
return -1; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment