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