4 tgetopt -- POSIX-compliant implementation of getopt() with string-type-generic
7 This is public domain software
20 int _tgetopt(int argc, _TCHAR * const argv[], const _TCHAR * optstring)
22 static int s_nArgChar = 0;
26 if(_toptind >= argc) return -1;
28 /* last time we reached the end of argv[_toptind] */
29 if(s_nArgChar != 0 && argv[_toptind][s_nArgChar] == 0)
31 /* scan the next argument */
35 if(_toptind >= argc) return -1;
40 /* first time we scan argv[_toptind] */
43 /* argument is NULL - we're done */
44 if(argv[_toptind] == NULL)
46 /* argument is empty - we're done */
47 else if(argv[_toptind][0] == 0)
49 /* argument begins with '-' */
50 else if(argv[_toptind][0] == _T('-'))
52 /* argument is "--" */
53 if(argv[_toptind][1] == _T('-'))
55 /* increment optind */
63 else if(argv[_toptind][1] == 0)
72 /* argument doesn't begin with a dash - we're done */
77 /* return the current character */
78 _toptopt = argv[_toptind][s_nArgChar];
80 /* advance to the next character */
83 /* unrecognized option */
84 if(_toptopt == _T(':') || (pcOptChar = _tcschr(optstring, _toptopt)) == NULL)
86 /* print an error message */
87 if(_topterr && optstring[0] != _T(':'))
88 _ftprintf(stderr, _T("%s: illegal option -- %c\n"), argv[0], _toptopt);;
94 /* the option requires an argument */
95 if(pcOptChar[1] == _T(':'))
97 /* we are at the end of the argument */
98 if(argv[_toptind][s_nArgChar] == 0)
100 /* the argument of the option is the next argument */
104 /* this is the last argument */
107 /* print an error message */
108 if(_topterr && optstring[0] != _T(':'))
113 _T("%s: option requires an argument -- %c\n"),
119 /* return an error */
120 return ((optstring[0] == _T(':')) ? _T(':') : _T('?'));
123 /* return the argument */
124 _toptarg = argv[_toptind];
126 /* the rest of the argument is the argument of the option */
128 _toptarg = argv[_toptind] + s_nArgChar;