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 (fd: fileno (stderr), length: 0) != 0) |
23 | { |
24 | puts (s: "cannot truncate file" ); |
25 | return 1; |
26 | } |
27 | |
28 | int c = getopt_long (argc: argc, argv: argv, shortopts: fmt, longopts: opts, NULL); |
29 | if (c != expected[i]) |
30 | { |
31 | printf (format: "%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 (format: "%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 (format: "%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 (template: fname); |
58 | if (fd == -1) |
59 | { |
60 | printf (format: "mkstemp failed: %m\n" ); |
61 | return 1; |
62 | } |
63 | close (fd: fd); |
64 | |
65 | if (freopen (filename: fname, modes: "w+" , stderr) == NULL) |
66 | { |
67 | puts (s: "cannot redirect stderr" ); |
68 | return 1; |
69 | } |
70 | |
71 | remove (fname); |
72 | |
73 | int ret = one_test (fmt: "W;" , argc: 2, |
74 | argv: (char *[2]) { (char *) "bug-getopt4a" , (char *) "--a" }, |
75 | n: 1, expected: (int [1]) { 'a' }); |
76 | |
77 | ret |= one_test (fmt: "W;" , argc: 3, |
78 | argv: (char *[3]) { (char *) "bug-getopt4b" , (char *) "-W" , |
79 | (char *) "a" }, |
80 | n: 1, expected: (int [1]) { 'a' }); |
81 | |
82 | if (ret == 0) |
83 | puts (s: "all OK" ); |
84 | |
85 | return ret; |
86 | } |
87 | |
88 | #define TEST_FUNCTION do_test () |
89 | #include "../test-skeleton.c" |
90 | |