ungetc.c - scc - simple c99 compiler
 (HTM) git clone git://git.simple-cc.org/scc
 (DIR) Log
 (DIR) Files
 (DIR) Refs
 (DIR) Submodules
 (DIR) README
 (DIR) LICENSE
       ---
       ungetc.c (1088B)
       ---
            1 #include <stdio.h>
            2 
            3 /**
            4  * ungetc() - push back one character to a input stream
            5  *
            6  * Context: A stream just opened has rp, wp, lp and buf pointing to NULL,
            7  *          in the same way that a closed stream. In both cases we have to
            8  *          return EOF, so the check fp->rp == fp->buf detects both cases.
            9  *          An input stream can be either a read only input or a read and
           10  *          write input in read state, and we can detect the write state
           11  *          when wp does not point to the beginning of buf. _IOSTRG is used
           12  *          in sprintf/sscanf functions, where it is possible rp points to
           13  *          a constant string, so we cannot write back c, but it is safe
           14  *          because in those functions we are going to push back always
           15  *          the same character that the one contained in the string.
           16  */
           17 int
           18 ungetc(int c, FILE *fp)
           19 {
           20         if (c == EOF)
           21                 return EOF;
           22 
           23         if ((fp->flags & _IOWRITE) != 0)
           24                 return EOF;
           25 
           26         if (fp->rp == fp->buf || fp->wp != fp->buf)
           27                 return EOF;
           28 
           29         --fp->rp;
           30         if ((fp->flags & _IOSTRG) == 0)
           31                 *fp->rp = c;
           32         fp->flags &= ~_IOEOF;
           33 
           34         return c;
           35 }