Bump to release 1.4.0
[smenu.git] / fgetc.c
blob44e8eaab6506a06b6143596ea7d37ab43a9a86e8
1 /* ################################################################### */
2 /* Copyright 2015, Pierre Gentile (p.gen.progs@gmail.com) */
3 /* */
4 /* This Source Code Form is subject to the terms of the Mozilla Public */
5 /* License, v. 2.0. If a copy of the MPL was not distributed with this */
6 /* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
7 /* ################################################################### */
9 /* ************************************************************************* */
10 /* Custom fgetc/ungetc implementation able to unget more than one character. */
11 /* ************************************************************************* */
13 #include <stdio.h>
14 #include "fgetc.h"
16 enum
18 GETC_BUFF_SIZE = 16
21 static unsigned char getc_buffer[GETC_BUFF_SIZE] = { '\0' };
23 static long next_buffer_pos = 0; /* Next free position in the getc buffer. */
25 /* ======================================== */
26 /* Gets a (possibly pushed-back) character. */
27 /* ======================================== */
28 int
29 my_fgetc(FILE *input)
31 int c;
33 if (next_buffer_pos > 0)
34 return getc_buffer[--next_buffer_pos];
35 else
37 errno = 0;
38 c = fgetc(input);
40 while (c == EOF && errno == EAGAIN)
42 errno = 0;
43 c = fgetc(input);
46 return c;
50 /* =============================== */
51 /* Pushes character back on input. */
52 /* =============================== */
53 int
54 my_ungetc(int c, FILE *input)
56 int rc;
58 if (next_buffer_pos >= GETC_BUFF_SIZE)
59 rc = EOF;
60 else
62 rc = getc_buffer[next_buffer_pos++] = (unsigned char)c;
64 if (feof(input))
65 clearerr(input); /* No more EOF. */
68 return rc;