1de09c3776b2be01dda33c83c38f6d519bfa785d
[libc-test] / src / stdio / fscanf.c
1 #include <stdio.h>
2 #include <string.h>
3 #include <errno.h>
4 #include <limits.h>
5 #include <unistd.h>
6 #include "test.h"
7
8 #define T(r, f, x, m) do { \
9         r = (f); \
10         if (r != (x)) \
11                 error("%s failed (got %d, expected %d, errno \"%s\") (%s)\n", \
12                         #f, r, x, errno ? strerror(errno) : "", m); \
13         errno = 0; \
14 } while (0)
15
16 static void S(const char *s, const char *x, const char *m) {
17         if (strcmp(s, x) != 0)
18                 error("got [%s], expected [%s] (%s)\n", s, x, m);
19 }
20
21 void test_fscanf(void) {
22         int i, x, y;
23         char a[100], b[100];
24         int p[2];
25         FILE *f;
26
27         T(i, pipe(p), 0, "open pipe");
28         T(i, !(f = fdopen(p[0], "rb")), 0, "fdopen pipe");
29         if (!f) {
30                 close(p[0]);
31                 close(p[1]);
32                 return;
33         }
34
35         T(i, write(p[1], "hello, world\n", 13), 13, "write to pipe");
36         T(i, fscanf(f, "%s %[own]", a, b), 2, "");
37         S(a, "hello,", "wrong result for %s");
38         S(b, "wo", "wrong result for %[own]");
39         T(i, fgetc(f), 'r', "fgetc 'r'");
40
41         T(i, write(p[1], " 0x12 0x34", 10), 10, "");
42         T(i, fscanf(f, "ld %5i%2i", &x, &y), 1, "");
43         T(i, x, 0x12, "");
44         T(i, fgetc(f), '3', "fgetc '3'");
45
46         fclose(f);
47         close(p[1]);
48 }