initial check-in, version 0.5.0
[musl] / src / stdio / ungetc.c
1 #include "stdio_impl.h"
2
3 int ungetc(int c, FILE *f)
4 {
5         if (c == EOF) return c;
6
7         FLOCK(f);
8
9         /* Fail if unreadable or writing and unable to flush */
10         if ((f->flags & (F_ERR|F_NORD)) || (f->wpos && __oflow(f))) {
11                 FUNLOCK(f);
12                 return EOF;
13         }
14
15         /* Clear write mode */
16         f->wbase = f->wpos = f->wstop = f->wend = 0;
17
18         /* Put the file in read mode */
19         if (!f->rpos) f->rpos = f->rend = f->buf;
20
21         /* If unget buffer is already full, fail. */
22         if (f->rpos <= f->buf - UNGET) {
23                 FUNLOCK(f);
24                 return EOF;
25         }
26
27         /* Put a byte back into the buffer */
28         *--f->rpos = c;
29         f->flags &= ~F_EOF;
30
31         FUNLOCK(f);
32         return c;
33 }