initial check-in, version 0.5.0
[musl] / src / stdio / vfscanf.c
1 #include <stdio.h>
2 #include <string.h>
3 #include <errno.h>
4 #include <ctype.h>
5
6 #include "stdio_impl.h"
7 #include "__scanf.h"
8
9 static void f_read(rctx_t *r)
10 {
11         FILE *f = r->opaque;
12         if ((r->c = __uflow(f)) >= 0) r->l++;
13 }
14
15 int vfscanf(FILE *f, const char *fmt, va_list ap)
16 {
17         size_t l = strlen(fmt), i, result;
18         rctx_t r = { f_read, (void *)f, 0, isspace };
19         wchar_t fmt2[l+1];
20
21         if (l > 0x100000) {
22                 errno = ENOMEM;
23                 return -1;
24         }
25         for (i=0; i<=l; i++) fmt2[i] = (unsigned char)fmt[i];
26
27         FLOCK(f);
28
29         result = __scanf(&r, fmt2, ap);
30
31         if (r.u && r.c >= 0) {
32                 /* This code takes care of the case where the caller performs
33                  * a nonmatching scanf to leave a character in the unscan
34                  * buffer, followed by an unget, followed by a scanf that
35                  * matches zero characters. In this case the final 'unread'
36                  * character must be returned to the unget buffer rather than
37                  * the unscan buffer. */
38                  f->rpos--;
39         }
40
41         FUNLOCK(f);
42         return result;
43 }