summaryrefslogtreecommitdiffstats
path: root/fgetc.c
diff options
context:
space:
mode:
authorpgen <p.gen.progs@gmail.com>2018-09-29 14:57:23 +0200
committerpgen <p.gen.progs@gmail.com>2018-10-01 19:36:56 +0200
commit54a29e1c65c17851cff2dfcae6a7540c4d64f125 (patch)
tree2eda10cf03d52837b8b9a0e37425877263606c46 /fgetc.c
parent79ddfc36120edfedf8c7c2ea6ce4eff05fac4fb6 (diff)
Create fgetc.[ch]
Diffstat (limited to 'fgetc.c')
-rw-r--r--fgetc.c37
1 files changed, 37 insertions, 0 deletions
diff --git a/fgetc.c b/fgetc.c
new file mode 100644
index 0000000..4aaffeb
--- /dev/null
+++ b/fgetc.c
@@ -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;
+}