File: bug-getopt4.c

package info (click to toggle)
glibc 2.19-18+deb8u9
  • links: PTS, VCS
  • area: main
  • in suites: jessie
  • size: 204,712 kB
  • ctags: 145,148
  • sloc: ansic: 970,427; asm: 241,207; sh: 10,069; makefile: 8,476; cpp: 3,595; perl: 2,077; pascal: 1,839; awk: 1,704; yacc: 317; sed: 73
file content (86 lines) | stat: -rw-r--r-- 1,664 bytes parent folder | download | duplicates (18)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
/* BZ 11041 */
#include <getopt.h>
#include <unistd.h>
#include <stdio.h>

static const struct option opts[] =
  {
    { "alpha",    optional_argument, NULL, 'a' },
    { NULL,       0,                 NULL, 0 }
  };

static int
one_test (const char *fmt, int argc, char *argv[], int n, int expected[n])
{
  optind = 1;

  int res = 0;
  for (int i = 0; i < n; ++i)
    {
      rewind (stderr);
      if (ftruncate (fileno (stderr), 0) != 0)
	{
	  puts ("cannot truncate file");
	  return 1;
	}

      int c = getopt_long (argc, argv, fmt, opts, NULL);
      if (c != expected[i])
	{
	  printf ("format '%s' test %d failed: expected '%c', got '%c'\n",
		  fmt, i, expected[i], c);
	  res = 1;
	}
      else if (optarg != NULL)
	{
	  printf ("format '%s' test %d failed: optarg is \"%s\", not NULL\n",
		  fmt, i, optarg);
	  res = 1;
	}
      if (ftell (stderr) != 0)
	{
	  printf ("format '%s' test %d failed: printed to stderr\n",
		  fmt, i);
	  res = 1;
	}
    }

  return res;
}


static int
do_test (void)
{
  char *fname = tmpnam (NULL);
  if (fname == NULL)
    {
      puts ("cannot generate name for temporary file");
      return 1;
    }

  if (freopen (fname, "w+", stderr) == NULL)
    {
      puts ("cannot redirect stderr");
      return 1;
    }

  remove (fname);

  int ret = one_test ("W;", 2,
		      (char *[2]) { (char *) "bug-getopt4", (char *) "--a" },
		      1, (int [1]) { 'a' });

  ret |= one_test ("W;", 3,
		   (char *[3]) { (char *) "bug-getopt4", (char *) "-W",
				 (char *) "a" },
		   1, (int [1]) { 'a' });

  if (ret == 0)
    puts ("all OK");

  return ret;
}

#define TEST_FUNCTION do_test ()
#include "../test-skeleton.c"