website

Website contents
git clone git://git.reagancfischer.dev/website.git
Log | Files | Refs

input.c (1034B)


      1 /* input.c */
      2 #include <stdio.h>
      3 #include <stdlib.h>
      4 #include "input.h"
      5 /* Input Data */
      6 #define CHUNK_SIZE 128
      7 static char buffer[CHUNK_SIZE];
      8 static int buffer_pos = 0;
      9 static int buffer_size = 0;
     10 static char unget_buffer_stack[8];
     11 static int unget_buffer_stack_pos = 0;
     12 
     13 static FILE *file = NULL;
     14 
     15 /* Input Initialization */
     16 void input_init(const char *filename) {
     17   file = fopen(filename, "r");
     18   if (file == NULL) {
     19     fprintf(stderr, "Error: Cannot open file %s\n", filename);
     20     exit(1);
     21   }
     22 }
     23 
     24 /* Input Get Character */
     25 int input_getc(void) {
     26   if (unget_buffer_stack_pos > 0) {
     27     return unget_buffer_stack[--unget_buffer_stack_pos];
     28   }
     29   if (buffer_pos == buffer_size) {
     30     buffer_size = fread(buffer, 1, CHUNK_SIZE, file);
     31     buffer_pos = 0;
     32   }
     33   if (buffer_size == 0) {
     34     return EOF;
     35   }
     36   char c = buffer[buffer_pos++];
     37   return c;
     38 }
     39 
     40 /* Input Unget Character */
     41 void input_ungetc(int c) {
     42   unget_buffer_stack[unget_buffer_stack_pos++] = c;
     43 }
     44 
     45 /* Input Destroy */
     46 void input_destroy(void) {
     47   fclose(file);
     48 }
     49 
     50