4 tgetopt -- POSIX-compliant implementation of getopt() with string-type-generic
7 This is public domain software
21 int _tgetopt(int argc
, _TCHAR
* const argv
[], const _TCHAR
* optstring
)
23 static int s_nArgChar
= 0;
27 if(_toptind
>= argc
) return -1;
29 /* last time we reached the end of argv[_toptind] */
30 if(s_nArgChar
!= 0 && argv
[_toptind
][s_nArgChar
] == 0)
32 /* scan the next argument */
36 if(_toptind
>= argc
) return -1;
41 /* first time we scan argv[_toptind] */
44 /* argument is NULL - we're done */
45 if(argv
[_toptind
] == NULL
)
47 /* argument is empty - we're done */
48 else if(argv
[_toptind
][0] == 0)
50 /* argument begins with '-' */
51 else if(argv
[_toptind
][0] == _T('-'))
53 /* argument is "--" */
54 if(argv
[_toptind
][1] == _T('-'))
56 /* increment optind */
64 else if(argv
[_toptind
][1] == 0)
73 /* argument doesn't begin with a dash - we're done */
78 /* return the current character */
79 _toptopt
= argv
[_toptind
][s_nArgChar
];
81 /* advance to the next character */
84 /* unrecognized option */
85 if(_toptopt
== _T(':') || (pcOptChar
= _tcschr(optstring
, _toptopt
)) == NULL
)
87 /* print an error message */
88 if(_topterr
&& optstring
[0] != _T(':'))
89 _ftprintf(stderr
, _T("%s: illegal option -- %c\n"), argv
[0], _toptopt
);
95 /* the option requires an argument */
96 if(pcOptChar
[1] == _T(':'))
98 /* we are at the end of the argument */
99 if(argv
[_toptind
][s_nArgChar
] == 0)
101 /* the argument of the option is the next argument */
105 /* this is the last argument */
108 /* print an error message */
109 if(_topterr
&& optstring
[0] != _T(':'))
114 _T("%s: option requires an argument -- %c\n"),
120 /* return an error */
121 return ((optstring
[0] == _T(':')) ? _T(':') : _T('?'));
124 /* return the argument */
125 _toptarg
= argv
[_toptind
];
128 /* the rest of the argument is the argument of the option */
130 _toptarg
= argv
[_toptind
] + s_nArgChar
;