summaryrefslogtreecommitdiffstats
path: root/fgetc.c
blob: f6a9e9343c77ded0b62765a8aab4f1ff8ec4669e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
/* ########################################################### */
/* This Software is licensed under the GPL licensed Version 2, */
/* please read http://www.gnu.org/copyleft/gpl.html.           */
/* ########################################################### */

/* ************************************************************************* */
/* Custom fgetc/ungetc implementation able to unget more than one character. */
/* ************************************************************************* */

#include <stdio.h>
#include "fgetc.h"

enum
{
  GETC_BUFF_SIZE = 16
};

static unsigned char getc_buffer[GETC_BUFF_SIZE] = { '\0' };

static long next_buffer_pos = 0; /* Next free position in the getc buffer. */

/* ======================================== */
/* Gets a (possibly pushed-back) character. */
/* ======================================== */
int
my_fgetc(FILE * input)
{
  return (next_buffer_pos > 0) ? getc_buffer[--next_buffer_pos] : fgetc(input);
}

/* =============================== */
/* Pushes character back on input. */
/* =============================== */
int
my_ungetc(int c, FILE * input)
{
  int rc;

  if (next_buffer_pos >= GETC_BUFF_SIZE)
  {
    fprintf(stderr, "Error: cannot push back more than %d characters\n",
            GETC_BUFF_SIZE);
    rc = EOF;
  }
  else
  {
    rc = getc_buffer[next_buffer_pos++] = (unsigned char)c;

    if (feof(input))
      clearerr(input); /* No more EOF. */
  }

  return rc;
}