initial commit
[glibc.git] / posix / bug-getopt1.c
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 (fileno (stderr), 0) != 0)
16 {
17 puts ("cannot truncate file");
18 return 1;
19 }
20
21 int c = getopt (argc, argv, fmt);
22 if (c != expected[i])
23 {
24 printf ("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 '%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 (fname);
45 if (fd == -1)
46 {
47 printf ("mkstemp failed: %m\n");
48 return 1;
49 }
50 close (fd);
51
52 if (freopen (fname, "w+", stderr) == NULL)
53 {
54 puts ("cannot redirect stderr");
55 return 1;
56 }
57
58 remove (fname);
59
60 int ret = one_test ("+:a:b", 2,
61 (char *[2]) { (char *) "bug-getopt1", (char *) "-a" },
62 (int [1]) { ':' });
63
64 ret |= one_test ("+:a:b", 3,
65 (char *[3]) { (char *) "bug-getopt1", (char *) "-b",
66 (char *) "-a" },
67 (int [2]) { 'b', ':' });
68
69 if (ret == 0)
70 puts ("all OK");
71
72 return ret;
73 }
74
75 #define TEST_FUNCTION do_test ()
76 #include "../test-skeleton.c"