File: opt.c

package info (click to toggle)
sn 0.3.4a-2
  • links: PTS
  • area: main
  • in suites: woody
  • size: 784 kB
  • ctags: 826
  • sloc: ansic: 9,023; sh: 339; makefile: 208
file content (85 lines) | stat: -rw-r--r-- 1,968 bytes parent folder | download
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
/*
 * This file is part of the sn package.
 * Distribution of sn is covered by the GNU GPL. See file COPYING.
 * Copyright  1998-2000 Harold Tay.
 * Copyright  2000- Patrik Rdman.
 */

/*
 * alternative to getopt.  DOES NOT FOLLOW GETOPT STANDARD.
 * opts is string of flag chars for which an argument is expected.
 * opt_ind is current index to argv.  option flag is returned, unless
 * no options are found, then -1 is returned.  If that option flag
 * is in opts (has an associated value), that value is in opt_arg,
 * or NULL if no value was found.  Caller can set opt_ind to start
 * option checking at any point.
 */

static const char rcsid[] = "$Id$";

int opt_ind = 0;
char *opt_arg = 0;
static int opt_char = 0;

int opt_get (int c, char **v, char *opts)
{
   if (0 == opt_ind) opt_ind = 1;

   while (1)
   {
      if (opt_ind >= c)
         goto done;
      if (0 == opt_char)
      {
         if ('-' != v[opt_ind][opt_char])
            goto done;
         opt_char++;
         if ('-' == v[opt_ind][opt_char])
            if (!v[opt_ind][opt_char + 1])
            {
               opt_arg = 0;
               opt_char = 0;
               return (-1);
            }
         if (!v[opt_ind][opt_char]) /* bare dash */
            goto noarg;
      }
      if (!v[opt_ind][opt_char])
      {
         opt_ind++;
         opt_char = 0;
         continue;
      }
      break;
   }

   for (; *opts && *opts != v[opt_ind][opt_char]; opts++) ;
   if (!*opts)
      goto noarg;

   if (!v[opt_ind][opt_char + 1]) /* arg not catted with flag */
   {
      if (opt_ind + 1 == c)
      {
         opt_arg = 0;
         return (*opts);
      }
      opt_arg = v[opt_ind + 1];
      opt_ind += 2;
   }
   else /* arg catted with flag */
   {
      opt_arg = v[opt_ind] + opt_char + 1;
      opt_ind++;
   }
   opt_char = 0;
   return (*opts);

noarg:
   opt_arg = 0;
   return (v[opt_ind][opt_char++]);
done:
   opt_arg = 0;
   opt_char = 0;
   return (-1);
}