1 /* BZ 11039 */
2 #include <unistd.h>
3 #include <stdio.h>
4 #include <stdlib.h>
5 
6 static int
one_test(const char * fmt,int argc,char * argv[],int expected[argc-1])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 (fileno (stderr), 0) != 0)
14 	{
15 	  puts ("cannot truncate file");
16 	  return 1;
17 	}
18 
19       int c = getopt (argc, argv, fmt);
20       if (c != expected[i])
21 	{
22 	  printf ("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 '%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
do_test(void)39 do_test (void)
40 {
41   char fname[] = "/tmp/bug-getopt2.XXXXXX";
42   int fd = mkstemp (fname);
43   if (fd == -1)
44     {
45       printf ("mkstemp failed: %m\n");
46       return 1;
47     }
48   close (fd);
49 
50   if (freopen (fname, "w+", stderr) == NULL)
51     {
52       puts ("cannot redirect stderr");
53       return 1;
54     }
55 
56   remove (fname);
57 
58   optind = 0;
59   int ret = one_test ("+a", 2,
60 		      (char *[2]) { (char *) "bug-getopt2", (char *) "-+" },
61 		      (int [1]) { '?' });
62 
63   optind = 1;
64   ret |= one_test ("+a", 2,
65 		   (char *[2]) { (char *) "bug-getopt2", (char *) "-+" },
66 		   (int [1]) { '?' });
67 
68   if (ret == 0)
69     puts ("all OK");
70 
71   return ret;
72 }
73 
74 #define TEST_FUNCTION do_test ()
75 #include "../test-skeleton.c"
76