home *** CD-ROM | disk | FTP | other *** search
- #include <errno.h>
- #include <string.h>
- #include <dos.h>
- #include <stdio.h>
- #include <ctype.h>
- #include <alloc.h>
- #include "getopt.h"
-
- int aindex; // argument index
- int oindex; // option index
- int margc; // number of arguments
- char **margv; // the arguments itself
- char *moptions; // option string
- char switchchar; // switch char
- char *op,*np; //
- char dest[160]; // dest is large enough to hold a complete commandline
- char c; // last option char
-
-
-
- int GetNextPartial(void)
- /*
- Copy next commandline argument into dest[]. This functions
- splits arguments like BLAHBLAH/X/Y into separate argument i.e.
- BLAHBLAH, /X and /Y. This makes parsing the switches a lot easier.
-
- returns: 1 on succes
- 0 on end of commandline
- */
- {
- if(op==NULL){
- op=margv[aindex++];
- if(op==NULL) return 0;
- }
-
- if((np=strchr(op+1,switchchar))!=NULL){
- *np=0;
- strcpy(dest,op);
- *np=switchchar;
- }
- else{
- strcpy(dest,op);
- }
-
- op=np;
- return 1;
- }
-
-
-
-
- void InitOpt(int argc,char *argv[],char *options)
- /*
- Initializes commandline parsing:
-
- input: argc - standard argument count, as delivered to main()
- argv[] - standard argument array, as delivered to main()
- options - a string of option-characters to scan for. When an
- option is followed by ':' that option will require an
- argument.
- */
- {
- _AX = 0x3700; // get dos switch character via doscall
- geninterrupt(0x21);
- switchchar=_DL;
- margc=argc; // init global vars.
- margv=argv;
- moptions=options;
- aindex=1; // reset current argument index
- oindex=1; // reset current option index
- op=NULL;
- c=0;
- }
-
-
-
-
- int GetOpt(char *opt,char **arg)
- /*
- Get next commandline element (option, option+argument or argument)
-
- returns:
- GO_EOF no more elements
- GO_OPT option char in opt, option argument in arg
- GO_ARG normal argument (..filename) in arg
- GO_UNKNOWN_SWITCH the option in opt is not valid
- GO_SWITCH_NEEDS_ARG the option in opt needs an argument
-
- Yes, yes.. this is a really messy routine.. but it does the job. If
- anyone knows a cleaner or smaller method, let me know.
- */
- {
- char *p,*marg;
-
- nextarg:
-
- if(c==0) if(!GetNextPartial()) return GO_EOF;
-
- if(dest[0]==switchchar){
-
- c=dest[oindex++];
- *opt=c;
- *arg=NULL;
-
- if(c==0){
- if(oindex==2) return GO_UNKNOWN_SWITCH; // no empty switch
- oindex=1;
- goto nextarg; // <- don't try this at home kids!
- }
-
- if(c==':' || (p=strchr(moptions,c))==NULL){
- return GO_UNKNOWN_SWITCH;
- }
-
- if(p[1]==':'){
-
- if(dest[oindex]==0){
- if(!GetNextPartial() || dest[0]==switchchar){
- return GO_SWITCH_NEEDS_ARG;
- }
- *arg=dest;
- }
- else{
- *arg=&dest[oindex];
- }
- oindex=1;
- c=0;
- }
-
- return GO_OPT;
- }
- else{
- *arg=dest;
- oindex=1;
- c=0;
- return GO_ARG;
- }
- }
-
-
-