summaryrefslogtreecommitdiff
path: root/src/stdio/ungetwc.c
diff options
context:
space:
mode:
authorRich Felker <dalias@aerifal.cx>2011-02-12 00:22:29 -0500
committerRich Felker <dalias@aerifal.cx>2011-02-12 00:22:29 -0500
commit0b44a0315b47dd8eced9f3b7f31580cf14bbfc01 (patch)
tree6eaef0d8a720fa3da580de87b647fff796fe80b3 /src/stdio/ungetwc.c
downloadmusl-0b44a0315b47dd8eced9f3b7f31580cf14bbfc01.tar.gz
initial check-in, version 0.5.0v0.5.0
Diffstat (limited to 'src/stdio/ungetwc.c')
-rw-r--r--src/stdio/ungetwc.c45
1 files changed, 45 insertions, 0 deletions
diff --git a/src/stdio/ungetwc.c b/src/stdio/ungetwc.c
new file mode 100644
index 00000000..f7cde2e0
--- /dev/null
+++ b/src/stdio/ungetwc.c
@@ -0,0 +1,45 @@
+#include "stdio_impl.h"
+
+wint_t ungetwc(wint_t c, FILE *f)
+{
+ unsigned char mbc[MB_LEN_MAX];
+ int l=1;
+
+ if (c == WEOF) return c;
+
+ /* Try conversion early so we can fail without locking if invalid */
+ if (!isascii(c) && (l = wctomb(mbc, c)) < 0)
+ return WEOF;
+
+ FLOCK(f);
+
+ f->mode |= f->mode+1;
+
+ /* Fail if unreadable or writing and unable to flush */
+ if ((f->flags & (F_ERR|F_NORD)) || (f->wpos && __oflow(f))) {
+ FUNLOCK(f);
+ return EOF;
+ }
+
+ /* Clear write mode */
+ f->wpos = f->wstop = f->wend = 0;
+
+ /* Put the file in read mode */
+ if (!f->rpos) f->rpos = f->rend = f->buf;
+
+ /* If unget buffer is nonempty, fail. */
+ if (f->rpos < f->buf) {
+ FUNLOCK(f);
+ return WEOF;
+ }
+
+ /* Put character back into the buffer */
+ if (isascii(c)) *--f->rpos = c;
+ else memcpy(f->rpos -= l, mbc, l);
+
+ /* Clear EOF */
+ f->flags &= ~F_EOF;
+
+ FUNLOCK(f);
+ return c;
+}