File: mygetopt.c

package info (click to toggle)
latex2rtf 1.8aa-2
  • links: PTS
  • area: main
  • in suites: potato
  • size: 1,300 kB
  • ctags: 535
  • sloc: ansic: 5,434; makefile: 231; sh: 4
file content (88 lines) | stat: -rw-r--r-- 2,196 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
86
87
88
/*  $Id: mygetopt.c,v 1.1 1998/11/12 13:05:43 glehner Exp $
 *  History:
 * $Log: mygetopt.c,v $
 * Revision 1.1  1998/11/12 13:05:43  glehner
 * Initial revision
 *
 *
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "main.h"

/* my_getopt  is supposed to emulate the C Library getopt
   (which, according to the man pages, is written by Henry Spencer
   to emulate the Bell Lab version).

   my_getopt is scanning argv[optind] (and, perhaps, following
   arguments), looking for the first option starting with `-' and a
   character from optstring[]. Therefore, if you are looking
   for options in argv[1] etc., you should initialize optind
   with 1 (not 0, as the manual erroneously claims).

   Experiments with getopt() established that when an argument
   consists of more than one option, getopt() stores the
   pointer to the beginning of the argument as a static
   variable, for re-use later.

   See the getopt manual pages for more information on getopt.



   Written by V.Menkov, IU, 1995

*/

extern  char * optarg;
extern  int optind;

typedef int logical;

int my_getopt(int argc, char ** argv, char * optstring) {
  char *q;
  static char * rem = NULL;
  int c;
  logical needarg = 0;

  optarg = NULL;

  diagnostics(4, "Processing option `%s'", argv[optind]);

  /*  printf("optind = %d\n", optind);  if (rem) printf("rem=`%s'\n", rem);*/

    if (!rem) {
    if (optind < argc && argv[optind][0] == '-') {
      rem = argv[optind]+1;
      if (*rem == 0) return EOF;     /* Treat lone "-" as a non-option arg */
      if (*rem == '-') { optind++; return EOF;}  /* skip "--" and terminate */
    }
    else return EOF;
    }

  c = *rem;
  q = strchr(optstring, c);
  if (q && c != ':') {              /* matched */
    needarg = (q[1] == ':');
    if (needarg) {
      if (rem[1] != 0) optarg = rem + 1;
      else {
	optind ++;
	if (optind < argc) optarg = argv[optind];
	else {
	  fprintf(stderr, "Missing argument after -%c\n", c);
	  exit(1);
	}
      }
    } else rem ++;
  } else {
    fprintf(stderr, "%s: illegal option -- %c\n", argv[0], c);
    c = '?';
    rem ++;
  }
  if (needarg || *rem == 0) { rem = NULL; optind++;}
  return c;
}