1#include <stdio.h>23/**4 * ungetc() - push back one character to a input stream5 *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 to8 * 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 and10 * write input in read state, and we can detect the write state11 * when wp does not point to the beginning of buf. _IOSTRG is used12 * in sprintf/sscanf functions, where it is possible rp points to13 * a constant string, so we cannot write back c, but it is safe14 * because in those functions we are going to push back always15 * the same character that the one contained in the string.16 */17int18ungetc(int c, FILE *fp)19{20 if (c == EOF)21 return EOF;2223 if ((fp->flags & _IOWRITE) != 0)24 return EOF;2526 if (fp->rp == fp->buf || fp->wp != fp->buf)27 return EOF;2829 --fp->rp;30 if ((fp->flags & _IOSTRG) == 0)31 *fp->rp = c;32 fp->flags &= ~_IOEOF;3334 return c;35}