Get a character from the stdin, put it into a buffer (which has a size of BUFSIZE).
  • getch gets a character out of the buffer (if stdin is finished, an EOF is returned).
  • fgetch replaces stdin by a file.
  • ungetch puts back a character into the buffer.

  • #include <stdio.h>
    #include "getch.h"
    
    char buf[BUFSIZE];
    int sp = 0;
    
    int getch(void) {
        return (sp > 0) ? buf[--sp] : getchar();
    }
    
    int fgetch(FILE *fp) {
        return (sp > 0) ? buf[--sp] : getc(fp);
    }
    
    void ungetch(int c) {
        if (sp >= BUFSIZE)
    	fprintf(stderr, "ERROR.  ungetch: buffer is full.\n");
        else
    	buf[sp++] = c;
    }
    

    Created: Nov 26, 1994
    Last Revised: Dec 6, 1994
    © Copyright 1994 Wei-Chang Shann

    shann@math.ncu.edu.tw