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 | { "a1" , no_argument, NULL, 'a' }, |
10 | { "a2" , no_argument, NULL, 'a' }, |
11 | { NULL, 0, NULL, 0 } |
12 | }; |
13 | |
14 | static int |
15 | one_test (const char *fmt, int argc, char *argv[], int n, int expected[n]) |
16 | { |
17 | optind = 1; |
18 | |
19 | int res = 0; |
20 | for (int i = 0; i < n; ++i) |
21 | { |
22 | rewind (stderr); |
23 | if (ftruncate (fd: fileno (stderr), length: 0) != 0) |
24 | { |
25 | puts (s: "cannot truncate file" ); |
26 | return 1; |
27 | } |
28 | |
29 | int c = getopt_long (argc: argc, argv: argv, shortopts: fmt, longopts: opts, NULL); |
30 | if (c != expected[i]) |
31 | { |
32 | printf (format: "format '%s' test %d failed: expected '%c', got '%c'\n" , |
33 | fmt, i, expected[i], c); |
34 | res = 1; |
35 | } |
36 | if (ftell (stderr) != 0) |
37 | { |
38 | printf (format: "format '%s' test %d failed: printed to stderr\n" , |
39 | fmt, i); |
40 | res = 1; |
41 | } |
42 | } |
43 | |
44 | return res; |
45 | } |
46 | |
47 | |
48 | static int |
49 | do_test (void) |
50 | { |
51 | char fname[] = "/tmp/bug-getopt5.XXXXXX" ; |
52 | int fd = mkstemp (template: fname); |
53 | if (fd == -1) |
54 | { |
55 | printf (format: "mkstemp failed: %m\n" ); |
56 | return 1; |
57 | } |
58 | close (fd: fd); |
59 | |
60 | if (freopen (filename: fname, modes: "w+" , stderr) == NULL) |
61 | { |
62 | puts (s: "cannot redirect stderr" ); |
63 | return 1; |
64 | } |
65 | |
66 | remove (fname); |
67 | |
68 | int ret = one_test (fmt: ":W;" , argc: 2, |
69 | argv: (char *[2]) { (char *) "bug-getopt5" , (char *) "--a" }, |
70 | n: 1, expected: (int [1]) { 'a' }); |
71 | |
72 | ret |= one_test (fmt: ":W;" , argc: 3, |
73 | argv: (char *[3]) { (char *) "bug-getopt5" , (char *) "-W" , |
74 | (char *) "a" }, |
75 | n: 1, expected: (int [1]) { 'a' }); |
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 | |