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