posix: Remove alloca usage for internal fnmatch implementation
[platform/upstream/glibc.git] / posix / bug-getopt4.c
1 /* BZ 11041 */
2 #include <getopt.h>
3 #include <unistd.h>
4 #include <stdio.h>
5 #include <stdlib.h>
6
7 static const struct option opts[] =
8   {
9     { "alpha",    optional_argument, NULL, 'a' },
10     { NULL,       0,                 NULL, 0 }
11   };
12
13 static int
14 one_test (const char *fmt, int argc, char *argv[], int n, int expected[n])
15 {
16   optind = 1;
17
18   int res = 0;
19   for (int i = 0; i < n; ++i)
20     {
21       rewind (stderr);
22       if (ftruncate (fileno (stderr), 0) != 0)
23         {
24           puts ("cannot truncate file");
25           return 1;
26         }
27
28       int c = getopt_long (argc, argv, fmt, opts, NULL);
29       if (c != expected[i])
30         {
31           printf ("%s: format '%s' test %d failed: expected '%c', got '%c'\n",
32                   argv[0], fmt, i, expected[i], c);
33           res = 1;
34         }
35       else if (optarg != NULL)
36         {
37           printf ("%s: format '%s' test %d failed: optarg is \"%s\", not NULL\n",
38                   argv[0], fmt, i, optarg);
39           res = 1;
40         }
41       if (ftell (stderr) != 0)
42         {
43           printf ("%s: format '%s' test %d failed: printed to stderr\n",
44                   argv[0], fmt, i);
45           res = 1;
46         }
47     }
48
49   return res;
50 }
51
52
53 static int
54 do_test (void)
55 {
56   char fname[] = "/tmp/bug-getopt4.XXXXXX";
57   int fd = mkstemp (fname);
58   if (fd == -1)
59     {
60       printf ("mkstemp failed: %m\n");
61       return 1;
62     }
63   close (fd);
64
65   if (freopen (fname, "w+", stderr) == NULL)
66     {
67       puts ("cannot redirect stderr");
68       return 1;
69     }
70
71   remove (fname);
72
73   int ret = one_test ("W;", 2,
74                       (char *[2]) { (char *) "bug-getopt4a", (char *) "--a" },
75                       1, (int [1]) { 'a' });
76
77   ret |= one_test ("W;", 3,
78                    (char *[3]) { (char *) "bug-getopt4b", (char *) "-W",
79                                  (char *) "a" },
80                    1, (int [1]) { 'a' });
81
82   if (ret == 0)
83     puts ("all OK");
84
85   return ret;
86 }
87
88 #define TEST_FUNCTION do_test ()
89 #include "../test-skeleton.c"