Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <ctype.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <unistd.h>
- #include <getopt.h>
- int
- main (int argc, char **argv)
- {
- enum
- {
- T, TH, D, BUTT
- };
- const char *other_options[]=
- {
- [T] = "t",
- [TH] = "u",
- [D] = "cc",
- [BUTT] = NULL
- };
- int aflag = 0;
- int bflag = 0;
- char *cvalue = NULL;
- int index;
- int c;
- opterr = 0;
- /* for subopts within opts */
- char *subopts;
- char *value;
- /* required arguments use : after them
- optional arguments :: after them */
- static char string_options[]=
- "ab::c:df::e:";
- static struct option long_options[]=
- { /* required_argument 1 { : }
- optional_argument 2 { ::} */
- {"alpha",0,0,'a'},
- {"beta",0,0,'b'},
- {"charlie",1,0,'c'},
- {"delta",0,0,'d'},
- {"echo",1,0,'e'},
- {"foxtrot",0,0,'f'},
- {0,0,0,0} // required at end
- };
- while ((c = getopt_long_only (argc, argv,
- string_options,long_options,
- &index)) != -1)
- {
- switch (c)
- {
- case 'a':
- aflag = 1;
- printf("alpha %s: aflag=%d\n",
- optarg,aflag);
- break;
- case 'b':
- bflag = 1;
- printf("beta %s: bflag=%d\n",
- optarg,bflag);
- break;
- case 'c':
- if(optarg == NULL)
- printf("argument is required\n");
- cvalue = optarg;
- printf("\ncvalue= %s\noptarg= %s\n",
- cvalue,optarg);
- break;
- case 'd':
- printf("delta\n");
- break;
- case '?':
- if (optopt == 'c')
- fprintf (stderr, "Option -%c "
- "requires an argument.\n", optopt);
- else if (isprint (optopt))
- fprintf (stderr, "Unknown option"
- " `-%c'.\n", optopt);
- else
- fprintf (stderr,
- "Unknown option "
- "character `\\x%x'.\n",
- optopt);
- break;
- case 'e':
- subopts=optarg;
- while(*subopts != '\0')
- {
- switch(getsubopt(&subopts,
- (char **)other_options,
- &value))
- { //cli ./programName -e t=value
- case T:
- if(value == NULL)
- printf("value in"
- " subopt not "
- "present\n");
- else
- printf("subopt value\n"
- " = %s\n",value);
- break;
- default:
- printf("unknown < %s >\n",
- value);
- exit(1);
- break;
- } //end switch subopt
- break;
- }//end while subopt
- case 'f':
- printf("foxtrot\n");
- break;
- default:
- abort ();
- break;
- } // end 1st switch
- } // 1st while
- printf ("aflag = %d, bflag = %d, cvalue = %s\n",
- aflag, bflag, cvalue);
- for (index = optind; index < argc; index++)
- printf ("Non-option argument %s\n",
- argv[index]);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement