/* input.c */ #include #include #include "input.h" /* Input Data */ #define CHUNK_SIZE 128 static char buffer[CHUNK_SIZE]; static int buffer_pos = 0; static int buffer_size = 0; static char unget_buffer_stack[8]; static int unget_buffer_stack_pos = 0; static FILE *file = NULL; /* Input Initialization */ void input_init(const char *filename) { file = fopen(filename, "r"); if (file == NULL) { fprintf(stderr, "Error: Cannot open file %s\n", filename); exit(1); } } /* Input Get Character */ int input_getc(void) { if (unget_buffer_stack_pos > 0) { return unget_buffer_stack[--unget_buffer_stack_pos]; } if (buffer_pos == buffer_size) { buffer_size = fread(buffer, 1, CHUNK_SIZE, file); buffer_pos = 0; } if (buffer_size == 0) { return EOF; } char c = buffer[buffer_pos++]; return c; } /* Input Unget Character */ void input_ungetc(int c) { unget_buffer_stack[unget_buffer_stack_pos++] = c; } /* Input Destroy */ void input_destroy(void) { fclose(file); }