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

source code of glibc/posix/bug-getopt3.c