lh | 9ed821d | 2023-04-07 01:36:19 -0700 | [diff] [blame] | 1 | /* BZ 11041 */ |
| 2 | #include <getopt.h> |
| 3 | #include <unistd.h> |
| 4 | #include <stdio.h> |
| 5 | |
| 6 | static const struct option opts[] = |
| 7 | { |
| 8 | { "a1", no_argument, NULL, 'a' }, |
| 9 | { "a2", no_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 (fileno (stderr), 0) != 0) |
| 23 | { |
| 24 | puts ("cannot truncate file"); |
| 25 | return 1; |
| 26 | } |
| 27 | |
| 28 | int c = getopt_long (argc, argv, fmt, opts, NULL); |
| 29 | if (c != expected[i]) |
| 30 | { |
| 31 | printf ("format '%s' test %d failed: expected '%c', got '%c'\n", |
| 32 | fmt, i, expected[i], c); |
| 33 | res = 1; |
| 34 | } |
| 35 | if (ftell (stderr) != 0) |
| 36 | { |
| 37 | printf ("format '%s' test %d failed: printed to stderr\n", |
| 38 | fmt, i); |
| 39 | res = 1; |
| 40 | } |
| 41 | } |
| 42 | |
| 43 | return res; |
| 44 | } |
| 45 | |
| 46 | |
| 47 | static int |
| 48 | do_test (void) |
| 49 | { |
| 50 | char *fname = tmpnam (NULL); |
| 51 | if (fname == NULL) |
| 52 | { |
| 53 | puts ("cannot generate name for temporary file"); |
| 54 | return 1; |
| 55 | } |
| 56 | |
| 57 | if (freopen (fname, "w+", stderr) == NULL) |
| 58 | { |
| 59 | puts ("cannot redirect stderr"); |
| 60 | return 1; |
| 61 | } |
| 62 | |
| 63 | remove (fname); |
| 64 | |
| 65 | int ret = one_test (":W;", 2, |
| 66 | (char *[2]) { (char *) "bug-getopt5", (char *) "--a" }, |
| 67 | 1, (int [1]) { 'a' }); |
| 68 | |
| 69 | ret |= one_test (":W;", 3, |
| 70 | (char *[3]) { (char *) "bug-getopt5", (char *) "-W", |
| 71 | (char *) "a" }, |
| 72 | 1, (int [1]) { 'a' }); |
| 73 | |
| 74 | if (ret == 0) |
| 75 | puts ("all OK"); |
| 76 | |
| 77 | return ret; |
| 78 | } |
| 79 | |
| 80 | #define TEST_FUNCTION do_test () |
| 81 | #include "../test-skeleton.c" |