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