diff options
author | pgen <p.gen.progs@gmail.com> | 2018-09-29 14:57:23 +0200 |
---|---|---|
committer | pgen <p.gen.progs@gmail.com> | 2018-10-01 19:36:56 +0200 |
commit | 54a29e1c65c17851cff2dfcae6a7540c4d64f125 (patch) | |
tree | 2eda10cf03d52837b8b9a0e37425877263606c46 /fgetc.c | |
parent | 79ddfc36120edfedf8c7c2ea6ce4eff05fac4fb6 (diff) |
Create fgetc.[ch]
Diffstat (limited to 'fgetc.c')
-rw-r--r-- | fgetc.c | 37 |
1 files changed, 37 insertions, 0 deletions
@@ -0,0 +1,37 @@ +#include <stdio.h> +#include "fgetc.h" + +/* ************************************************************************ */ +/* Custom fgetc/ungetc implementation able to unget more than one character */ +/* ************************************************************************ */ + +enum +{ + GETC_BUFF_SIZE = 16 +}; + +static char getc_buffer[GETC_BUFF_SIZE] = { '\0' }; + +static long next_buffer_pos = 0; /* next free position in the getc buffer */ + +/* ====================================== */ +/* Get a (possibly pushed-back) character */ +/* ====================================== */ +int +my_fgetc(FILE * input) +{ + return (next_buffer_pos > 0) ? getc_buffer[--next_buffer_pos] : fgetc(input); +} + +/* ============================ */ +/* Push character back on input */ +/* ============================ */ +void +my_ungetc(int c) +{ + if (next_buffer_pos >= GETC_BUFF_SIZE) + fprintf(stderr, "Error: cannot push back more than %d characters\n", + GETC_BUFF_SIZE); + else + getc_buffer[next_buffer_pos++] = c; +} |