void CommandLineParser::parseArgs(const std::vector<StringView>& args, CommandLineFlags& result) const { size_t numPositionalConsumed = 0; size_t numFlagConsumed = 0; while (numFlagConsumed < args.size()) { auto flag = args[numFlagConsumed]; if (!isOption(flag)) // Positional arguments { if (numPositionalConsumed >= posFlagMap.size()) throw ParseException("too many positional arguments"); auto inserted = result.addFlag(posFlagMap[numPositionalConsumed].first, flag); assert(inserted && "Insertion failed"); ++numPositionalConsumed; } else // Optional arguments { flag.remove_prefix(1); // See if flag is "-help" if (flag == "help") throw HelpException(); auto itr = optFlagMap.find(flag); if (itr == optFlagMap.end()) throw ParseException("Option not recognized: " + flag.to_string()); if (itr->second.defaultValue) { ++numFlagConsumed; if (numFlagConsumed >= args.size()) throw ParseException("More argument needs to be provided after option " + flag.to_string()); auto flagArg = args[numFlagConsumed]; if (isOption(flagArg)) throw ParseException("Found another option instead of an argument after option " + flag.to_string()); auto inserted = result.addFlag(flag, flagArg); assert(inserted && "Insertion failed"); } else { auto inserted = result.addFlag(flag, ""); assert(inserted && "Insertion failed"); } } ++numFlagConsumed; } if (numPositionalConsumed < posFlagMap.size()) throw ParseException("Not enough positional arguments are provided"); for (auto const& mapping: optFlagMap) { if (mapping.second.defaultValue && result.lookup(mapping.first) == nullptr) result.addFlag(mapping.first, *mapping.second.defaultValue); } }
/* um zwischend en anzuzeigenden Modis zu schalten */ void MainWindow::changePage(QTreeWidgetItem*, int) { if(isOption()) {modeWidget->setCurrentIndex(1);} if(isOption()==2) {modeWidget->setCurrentIndex(2);} }
void CommandLineParser::parse() { while ( hasNextArgument() ) { getNextOption(); if ( isOption( "c", "compiler" ) ) m_useCompiler = true; else if ( isOption( "x", "xml" ) ) { m_useXml = true; m_xmlFileName = getNextOptionalParameter(); } else if ( isOption( "s", "xsl" ) ) m_xsl = getNextParameter(); else if ( isOption( "e", "encoding" ) ) m_encoding = getNextParameter(); else if ( isOption( "b", "brief-progress" ) ) m_briefProgress = true; else if ( isOption( "n", "no-progress" ) ) m_noProgress = true; else if ( isOption( "t", "text" ) ) m_useText = true; else if ( isOption( "o", "cout" ) ) m_useCout = true; else if ( isOption( "w", "wait" ) ) m_waitBeforeExit = true; else if ( !m_option.empty() ) fail( "Unknown option" ); else if ( hasNextArgument() ) readNonOptionCommands(); } }
void parse_repo(struct file_system_info *fsinfo, int argc, char** argv, int *index){ int i = 0; if (fsinfo->repo_count != 0) fail(ERR_PARAMETRES); for (i = *index; (i < argc) && (!isOption(argv[i])); i++){ }; fsinfo->repo_count = i - *index; fsinfo->repos = calloc(fsinfo->repo_count, sizeof(char *)); for (i = *index; (i < argc) && (!isOption(argv[i])); i++) gstrcpy(&fsinfo->repos[i - *index], argv[i]); *index += fsinfo->repo_count - 1; };
int parse(struct file_system_info *fsinfo, int argc, char **argv){ int i = 0; if ((argc == 2) && ((strcmp(argv[1], OPT_VERSION) == 0) || (strcmp(argv[1], OPT_VERSION_FULL) == 0))){ printf(PROGRAM_NAME " - filesystem in userspace for rdiff-backup repositories; version %s\n", PACKAGE_VERSION); exit(0); }; if (argc < 3) fail(ERR_PARAMETRES); for (i = 1; i < argc; i++){ if (isOption(argv[i]) == 1) parse_option(fsinfo, argc, argv, &i); else if (mount == NULL) parse_mount(argv[i]); else parse_repo(fsinfo, argc, argv, &i); }; if (mount == NULL) fail(ERR_NO_MOUNT); if (fsinfo->repo_count == 0) fail(ERR_NO_REPO); if ((layout == LAYOUT_LAST) && (structure != STRUCTURE_FULL)) fail(ERR_FULL_ONLY); return 0; };
int set_debug_level(int argc, char **argv, int *index){ if ((*index + 1 >= argc) || (isOption(argv[*index + 1]) == 1)) return -1; debug = 1; debug_level = atoi(argv[*index + 1]); *index += 1; return 0; }
bool ossimArgumentParser::containsOptions() const { for(int pos=1;pos<*theArgc;++pos) { if (isOption(pos)) return true; } return false; }
QString takeOptionValue(QStringList& arguments, int index) { QString result; if (index + 1 < arguments.count() && !isOption(arguments.at(index + 1))) result = arguments.takeAt(index + 1); arguments.removeAt(index); return result; }
bool CommandLineArgumentsParser::isThereUnkownOption(int argc, char** argv) { bool result(false); for(int i = 1; i < argc; ++i) { std::string argument(argv[i]); if( isOption(argument) ) { result = result || !isCorrectOption( argument ); } } return result; }
// wird aufgerufen, wenn ein Listenelement entfernt wird, um sicherzugehen... bool MainWindow::okToDelete() { if(!isOption()) { return false; } if(isOption()) {optOrRes = tr("Willst du diese Option wirklich lšschen?") ;} if(isOption() == 2) {optOrRes = tr("Willst du diese Antwort wirklich lšschen?") ;} int r = QMessageBox::warning(this, tr("RL-Dialog"), optOrRes, QMessageBox::Yes | QMessageBox::Default, QMessageBox::No, QMessageBox::Cancel | QMessageBox::Escape); if (r == QMessageBox::Yes) {return true; } else if (r == QMessageBox::Cancel) { return false; } return false; }
int add_fuse_option(int argc, char **argv, int *index){ if ((*index + 1 >= argc) || (isOption(argv[*index + 1]) == 1)) return -1; if (gmstrcpy(&fuse_options, "-o", argv[*index + 1], NULL)) return -1; *index += 1; return 0; };
int set_caching(int argc, char **argv, int *index){ if ((*index + 1 >= argc) || (isOption(argv[*index + 1]) == 1)) return -1; cache_limit = atoi(argv[*index + 1]); if (cache_limit < 0) return -1; *index += 1; return 0; };
int set_increments(int argc, char **argv, int *index){ if ((*index + 1 >= argc) || (isOption(argv[*index + 1]) == 1)) return -1; necessary_limit = atoi(argv[*index + 1]); if (cache_limit < 0) return -1; *index += 1; return 0; };
int set_directory(int argc, char **argv, int *index){ #define set_directory_finish(value) { \ if (temp != NULL) \ free(temp); \ return value; \ } struct stat *temp = NULL; if ((*index + 1 >= argc) || (isOption(argv[*index + 1]) == 1)) set_directory_finish(-1); temp = single(struct stat); if ((stat(argv[*index + 1], temp) != 0) || ((temp->st_mode & S_IFDIR) == 0)) set_directory_finish(-1); *index += 1; if (gstrcpy(&tmp_dir, argv[*index]) != 0) set_directory_finish(-1); set_directory_finish(0); };
/* * Input: argc, argv * Output: parameters parsed into structure Options * Memory allocation for options and parameters in here * return 1 if user asks for help, return 0 if no error, -1 if errors occur */ int parseOption(int const argc, char* const argv[]) { int i; //parse each option in turn for(i=1;i<argc;i++) { char* value=argv[i]; if(isOption(value)) { if(strcmp(value,"-help")==0) return 1; if (parseOneOption(value, argv, argc, &i) != 0) return 1; } } return 0; }
void ossimArgumentParser::reportRemainingOptionsAsUnrecognized(ossimErrorSeverity severity) { std::set<std::string> options; if (theUsage) { // parse the usage options to get all the option that the application can potential handle. for(ossimApplicationUsage::UsageMap::const_iterator itr=theUsage->getCommandLineOptions().begin(); itr!=theUsage->getCommandLineOptions().end(); ++itr) { const std::string& option = itr->first; std::string::size_type prevpos = 0, pos = 0; while ((pos=option.find(' ',prevpos))!=std::string::npos) { if (option[prevpos]=='-') { options.insert(std::string(option,prevpos,pos-prevpos)); } prevpos=pos+1; } if (option[prevpos]=='-') { options.insert(std::string(option,prevpos,std::string::npos)); } } } for(int pos=1;pos<argc();++pos) { // if an option and havn't been previous querried for report as unrecognized. if (isOption(pos) && options.find(theArgv[pos])==options.end()) { reportError(getApplicationName() +": unrecognized option "+theArgv[pos],severity); } } }
/** update parameter settings with command line switches * \param paramSwitch (potentially short) name of switch * \param paramName full name of parameter * \param argc number of arguments on command line * \param argv values of paramters on command line */ void Parameter::OverwriteParam(const string ¶mSwitch, const string ¶mName, int argc, char* argv[]) { int startPos = -1; for (int i = 0 ; i < argc ; i++) { if (string(argv[i]) == paramSwitch) { startPos = i+1; break; } } if (startPos < 0) return; int index = 0; m_setting[paramName]; // defines the parameter, important for boolean switches while (startPos < argc && (!isOption(argv[startPos]))) { if (m_setting[paramName].size() > (size_t)index) m_setting[paramName][index] = argv[startPos]; else m_setting[paramName].push_back(argv[startPos]); index++; startPos++; } }
void CommandLineArgumentsParser::parseArguments(int argc, char** argv) throw (std::invalid_argument){ if( !isArgumentEnough(argc) ) { throw std::invalid_argument("It is necessary to contain Class name."); } if( isContainLanguageSettingMultiple(argc, argv) ) { throw std::invalid_argument("Language Setting is contained once in arguments."); } if( isThereUnkownOption(argc, argv) ) { throw std::invalid_argument("Unknown Options are there."); } for(int i = 1; i < argc; ++i) { std::string argument(argv[i]); if( isOption(argument) ){ parseOption(argument); } else { className_.push_back(argv[i]); } } // return className_; }
static int parseOneOption (char *opt, char* const argv[], const int argc, int *pos) { if (strcmp(opt,"-activate") == 0) { ASSERT_HAS_NEXT(); char *o = argv[++(*pos)]; if (!hasCommandOption(o)) { errorMessage = o; return 1; } (*pos)++; (*pos) -= 2; setBoolOption(o,TRUE); return 0; } else if (strcmp(opt,"-deactivate") == 0) { ASSERT_HAS_NEXT(); char *o = argv[++(*pos)]; if (!hasCommandOption(o)) { errorMessage = o; return 1; } (*pos)++; (*pos) -= 2; setBoolOption(o,FALSE); return 0; } else if (hasCommandOption(opt)) { char *o = commandOptionGetOption(opt); (*pos)++; switch(getOptionType(o)) { case OPTION_INT: { ASSERT_HAS_NEXT(); int val = atoi(argv[*pos]); setIntOption(o,val); (*pos)++; (*pos) -= 2; } break; case OPTION_STRING: { ASSERT_HAS_NEXT(); setStringOption(o,strdup(argv[*pos])); (*pos)++; (*pos) -= 2; } break; case OPTION_FLOAT: { ASSERT_HAS_NEXT(); //TODO (*pos)++; (*pos) -= 2; } break; case OPTION_BOOL: // if user has given value as separate argument if (*pos < argc && !isOption(argv[*pos])) { char *bVal = argv[*pos]; if (streq(bVal,"TRUE") || streq(bVal,"t") || streq(bVal,"1") || streq(bVal,"true")) setBoolOption(o,TRUE); else setBoolOption(o,FALSE); } // otherwise mentioning an option sets it to TRUE else { setBoolOption(o, TRUE); (*pos) -= 1; } break; } return 0; } else { errorMessage = opt; return 1; } }
bool ossimArgumentParser::isOption(int pos) const { return pos<*theArgc && isOption(theArgv[pos]); }
void AddNew::processInput(string inputString) { // Holds the value entered by the user for this menu static int menuChoiceInt; static char menuChoiceChar; // Holds whether the entered value is valid static bool isValidInt; static bool isValidChar; isValidInt = validateInt(inputString, &menuChoiceInt); isValidChar = validateChar(inputString, &menuChoiceChar); if(isValidInt) { if(isOption(menuChoiceInt)) { // You need to find a way to associate values with menu selections // This more general than assuming the order that is setup in setActions() //process(); if(menuChoiceInt == 1) { //change(MenuSystem::ENTERDIR); kill(); } else if(menuChoiceInt == 2) { cout << "trying to switch to enter dir..." << endl; change(MenuSystem::ENTERDIR); //kill(); } else if(menuChoiceInt == 3) { //change(MenuSystem::REMOVEDIR); kill(); } else { process(); } } } else if(isValidChar) { if(Menu::isOption(menuChoiceChar)) { MenuSystem::MenuType menuType = getOption(menuChoiceChar)->getValue(); if(menuType == MenuSystem::EXIT) { kill(); } else if(menuType == MenuSystem::ADDREMOVE) { // Assuming there are no more menus for now change(MenuSystem::ADDREMOVE); } } else { printInvalidAndProcess(); } } else { printInvalidAndProcess(); } }
int main(int argc, char* argv[]) { char filename[512]; char filetoget[512]; char ofilename[512]; char outputformat[512]; char layoutformat[128]; char temp[512]; int loaderid; int interfacemode; int doublestep; HXCFLOPPYEMULATOR* hxcfe; verbose=0; doublestep=-1; hxcfe=hxcfe_init(); hxcfe_setOutputFunc(hxcfe,&CUI_affiche); printf("HxC Floppy Emulator : Floppy image file converter\n"); printf("Copyright (C) 2006-2013 Jean-Francois DEL NERO\n"); printf("This program comes with ABSOLUTELY NO WARRANTY\n"); printf("This is free software, and you are welcome to redistribute it\n"); printf("under certain conditions;\n\n"); printf("libhxcfe version : %s\n\n",hxcfe_getVersion(hxcfe)); // License print... if(isOption(argc,argv,"license",0)>0) { printf("License :\n%s\n\n",hxcfe_getLicense(hxcfe)); } // Verbose option... if(isOption(argc,argv,"verbose",0)>0) { printf("verbose mode\n"); verbose=1; } // help option... if(isOption(argc,argv,"help",0)>0) { printhelp(argv); } memset(filename,0,sizeof(filename)); // Input file name option if(isOption(argc,argv,"finput",(char*)&filename)>0) { printf("Input file : %s\n",filename); } // Output file name option memset(ofilename,0,512); isOption(argc,argv,"foutput",(char*)&ofilename); // Module list option if(isOption(argc,argv,"modulelist",0)>0) { printlibmodule(hxcfe); } // Interface mode list option if(isOption(argc,argv,"interfacelist",0)>0) { printinterfacemode(hxcfe); } // Interface mode list option if(isOption(argc,argv,"rawlist",0)>0) { printdisklayout(hxcfe); } // Interface mode option interfacemode=-1; if(isOption(argc,argv,"ifmode",(char*)&temp)>0) { interfacemode=hxcfe_getFloppyInterfaceModeID(hxcfe,temp); if(interfacemode<0) { printf("Unknown Interface mode ! : %s\n",temp); printf("Please use the -interfacelist option for possible interface modes.\n\n"); hxcfe_deinit(hxcfe); return -1; } } if(isOption(argc,argv,"infos",0)>0) { infofile(hxcfe,filename); } // Convert a file ? if(isOption(argc,argv,"conv",0)>0) { strcpy(outputformat,PLUGIN_HXC_HFE); isOption(argc,argv,"conv",(char*)&outputformat); loaderid=hxcfe_getLoaderID(hxcfe,outputformat); if(loaderid>=0) { if(!strlen(ofilename)) { get_filename(filename,ofilename); strcat(ofilename,"."); strcat(ofilename,hxcfe_getLoaderExt(hxcfe,loaderid)); } printf("Output file : %s\n",ofilename); } if(isOption(argc,argv,"uselayout",(char*)&layoutformat)>0) { convertrawfile(hxcfe,filename,layoutformat,ofilename,outputformat,interfacemode); } else { convertfile(hxcfe,filename,ofilename,outputformat,interfacemode); } } if(isOption(argc,argv,"singlestep",0)>0) { doublestep=0; } if(isOption(argc,argv,"doublestep",0)>0) { doublestep=0xFF; } if(isOption(argc,argv,"list",0)>0) { imagedir(hxcfe,filename); } if(isOption(argc,argv,"getfile",(char*)&filetoget)>0) { getfile(hxcfe,filename,filetoget); } if(isOption(argc,argv,"putfile",(char*)&filetoget)>0) { putfile(hxcfe,filename,filetoget); } // Input file name option if(isOption(argc,argv,"usb",(char*)&temp)>0) { usbload(hxcfe,filename,temp[0]-'0',doublestep,interfacemode); } if( (isOption(argc,argv,"help",0)<=0) && (isOption(argc,argv,"license",0)<=0) && (isOption(argc,argv,"modulelist",0)<=0) && (isOption(argc,argv,"interfacelist",0)<=0) && (isOption(argc,argv,"list",0)<=0) && (isOption(argc,argv,"getfile",0)<=0) && (isOption(argc,argv,"putfile",0)<=0) && (isOption(argc,argv,"conv",0)<=0) && (isOption(argc,argv,"usb",0)<=0) && (isOption(argc,argv,"rawlist",0)<=0) && (isOption(argc,argv,"infos",0)<=0 ) ) { printhelp(argv); } hxcfe_deinit(hxcfe); return 0; }
/* Input arguments have a pattern of -option argument -option argument For example -u username -p password where username is the name of the user who wishes to log in and password is the password for that user */ int parseArguments(int argc, char *argv[]) { // flag indicating the result bool passwordRequested = false; argumentInit(); // if the user did not pass any credentials, then take them from the config file /* if(argc == 1) getCredentialsFromConfigFile(); */ int i; for(i = 1; i < argc;) { if(argv[i][0] != '-') { fputs("Invalid Option\n", stderr); return -1; } char *option = argv[i]; if(strcmp(option, "-p") == 0){ passwordRequested = true; ++i; continue; } if(cfuhash_exists(arguments, option)) { char * argument = cfuhash_get(arguments, option); if(argument[0] != 0){ fputs("Criteria already set\n", stderr); return -1; } else if (i == argc - 1) { fputs("Invalid Argument Input\n", stderr); return -1; } else { if(isOption(argv[i + 1]) == 0) return -1; // calloc(30, (sizeof (char))); strlcpy(argument, argv[i + 1]); cfuhash_put(arguments, option, argument); i += 2; } } else { fputs("Option not recognised\n", stderr); return -1; } } if(passwordRequested) { fputs("Password: ", stdout); promptPasswordEntry(); } // TESTING // cfuhash_pretty_print(arguments, stdout); return 0; }
/** load all parameters from the configuration file and the command line switches */ bool Parameter::LoadParam(int argc, char* argv[]) { // config file (-f) arg mandatory string configPath; if ( (configPath = FindParam("-f", argc, argv)) == "" && (configPath = FindParam("-config", argc, argv)) == "") { PrintCredit(); Explain(); UserMessage::Add("No configuration file was specified. Use -config or -f"); return false; } else { if (!ReadConfigFile(configPath)) { UserMessage::Add("Could not read "+configPath); return false; } } // overwrite parameters with values from switches for(PARAM_STRING::const_iterator iterParam = m_description.begin(); iterParam != m_description.end(); iterParam++) { const string paramName = iterParam->first; OverwriteParam("-" + paramName, paramName, argc, argv); } // ... also shortcuts for(PARAM_STRING::const_iterator iterParam = m_abbreviation.begin(); iterParam != m_abbreviation.end(); iterParam++) { const string paramName = iterParam->first; const string paramShortName = iterParam->second; OverwriteParam("-" + paramShortName, paramName, argc, argv); } // logging of parameters that were set in either config or switch int verbose = 1; if (m_setting.find("verbose") != m_setting.end() && m_setting["verbose"].size() > 0) verbose = Scan<int>(m_setting["verbose"][0]); if (verbose >= 1) { // only if verbose TRACE_ERR( "Defined parameters (per moses.ini or switch):" << endl); for(PARAM_MAP::const_iterator iterParam = m_setting.begin() ; iterParam != m_setting.end(); iterParam++) { TRACE_ERR( "\t" << iterParam->first << ": "); for ( size_t i = 0; i < iterParam->second.size(); i++ ) TRACE_ERR( iterParam->second[i] << " "); TRACE_ERR( endl); } } // check for illegal parameters bool noErrorFlag = true; for (int i = 0 ; i < argc ; i++) { if (isOption(argv[i])) { string paramSwitch = (string) argv[i]; string paramName = paramSwitch.substr(1); if (m_valid.find(paramName) == m_valid.end()) { UserMessage::Add("illegal switch: " + paramSwitch); noErrorFlag = false; } } } // check if parameters make sense return Validate() && noErrorFlag; }
// --------------------------------------------------------------------------- // ^FUNCTION: Options::operator() - get options from the command-line // // ^SYNOPSIS: // int Options::operator()(iter, optarg) // // ^PARAMETERS: // OptIter & iter -- option iterator // const char * & optarg -- where to store any option-argument // // ^DESCRIPTION: // Parse the next option in iter (advancing as necessary). // Make sure we update the nextchar pointer along the way. Any option // we find should be returned and optarg should point to its argument. // // ^REQUIREMENTS: // None. // // ^SIDE-EFFECTS: // - iter is advanced when an argument is completely parsed // - optarg is modified to point to any option argument // - if Options::QUIET is not set, error messages are printed on cerr // // ^RETURN-VALUE: // 0 if all options have been parsed. // 'c' if the the option or long-option corresponding to the -c option was // matched (optarg points to its argument). // BADCHAR if the option is invalid (optarg points to the bad option char). // BADKWD if the option is invalid (optarg points to the bad long-opt name). // AMBIGUOUS if an ambiguous keyword name was given (optarg points to the // ambiguous keyword name). // POSITIONAL if PARSE_POS was set and the current argument is a positional // parameter (in which case optarg points to the positional argument). // // ^ALGORITHM: // It gets complicated -- follow the comments in the source. // ^^------------------------------------------------------------------------- int Options::operator()(OptIter & iter, const char * & optarg) { int parse_opts_only = isOptsOnly(optctrls); if (parse_opts_only) explicit_end = 0; // See if we have an option left over from before ... if ((nextchar) && *nextchar) { return parse_opt(iter, optarg); } // Check for end-of-options ... const char * arg = NULLSTR; int get_next_arg = 0; do { arg = iter.curr(); get_next_arg = 0; if (arg == NULL) { listopt = NULLSTR; return Options::ENDOPTS; } else if ((! explicit_end) && isEndOpts(arg)) { iter.next(); // advance past end-of-options arg listopt = NULLSTR; explicit_end = 1; if (parse_opts_only) return Options::ENDOPTS; get_next_arg = 1; // make sure we look at the next argument. } } while (get_next_arg); // Do we have a positional arg? if ( explicit_end || (! isOption(optctrls, arg)) ) { if (parse_opts_only) { return Options::ENDOPTS; } else { optarg = arg; // set optarg to the positional argument iter.next(); // advance iterator to the next argument return Options::POSITIONAL; } } iter.next(); // pass the argument that arg already points to // See if we have a long option ... if (! (optctrls & Options::SHORT_ONLY)) { if ((*arg == '-') && (arg[1] == '-')) { nextchar = arg + 2; return parse_longopt(iter, optarg); } else if ((optctrls & Options::PLUS) && (*arg == '+')) { nextchar = arg + 1; return parse_longopt(iter, optarg); } } if (*arg == '-') { nextchar = arg + 1; if (optctrls & Options::LONG_ONLY) { return parse_longopt(iter, optarg); } else { return parse_opt(iter, optarg); } } // If we get here - it is because we have a list value OptionSpec optspec = listopt; optarg = arg ; // record the list value return optspec.OptChar() ; }
// --------------------------------------------------------------------------- // ^FUNCTION: Options::parse_opt - parse an option // // ^SYNOPSIS: // int Options::parse_opt(iter, optarg) // // ^PARAMETERS: // OptIter & iter -- option iterator // const char * & optarg -- where to store any option-argument // // ^DESCRIPTION: // Parse the next option in iter (advancing as necessary). // Make sure we update the nextchar pointer along the way. Any option // we find should be returned and optarg should point to its argument. // // ^REQUIREMENTS: // - nextchar must point to the prospective option character // // ^SIDE-EFFECTS: // - iter is advanced when an argument completely parsed // - optarg is modified to point to any option argument // - if Options::QUIET is not set, error messages are printed on cerr // // ^RETURN-VALUE: // 'c' if the -c option was matched (optarg points to its argument) // BADCHAR if the option is invalid (optarg points to the bad // option-character). // // ^ALGORITHM: // It gets complicated -- follow the comments in the source. // ^^------------------------------------------------------------------------- int Options::parse_opt(OptIter & iter, const char * & optarg) { listopt = NULLSTR; // reset the list pointer if ((optvec == NULL) || (! *optvec)) return Options::ENDOPTS; // Try to match a known option OptionSpec optspec = match_opt(*(nextchar++), (optctrls & Options::ANYCASE)); // Check for an unknown option if (optspec.isNULL()) { // See if this was a long-option in disguise if (! (optctrls & Options::NOGUESSING)) { unsigned save_ctrls = optctrls; const char * save_nextchar = nextchar; nextchar -= 1; optctrls |= (Options::QUIET | Options::NOGUESSING); int optchar = parse_longopt(iter, optarg); optctrls = save_ctrls; if (optchar > 0) { return optchar; } else { nextchar = save_nextchar; } } if (! (optctrls & Options::QUIET)) { cerr << cmdname << ": unknown option -" << *(nextchar - 1) << "." << endl ; } optarg = (nextchar - 1); // record the bad option in optarg return Options::BADCHAR; } // If no argument is taken, then leave now if (optspec.isNoArg()) { optarg = NULLSTR; return optspec.OptChar(); } // Check for argument in this arg if (*nextchar) { optarg = nextchar; // the argument is right here nextchar = NULLSTR; // we've exhausted this arg if (optspec.isList()) listopt = optspec ; // save the list-spec return optspec.OptChar(); } // Check for argument in next arg const char * nextarg = iter.curr(); if ((nextarg != NULL) && (optspec.isValRequired() || (! isOption(optctrls, nextarg)))) { optarg = nextarg; // the argument is here iter.next(); // end of arg - advance if (optspec.isList()) listopt = optspec ; // save the list-spec return optspec.OptChar(); } // No argument given - if its required, thats an error optarg = NULLSTR; if (optspec.isValRequired() && !(optctrls & Options::QUIET)) { cerr << cmdname << ": argument required for -" << optspec.OptChar() << " option." << endl ; } return optspec.OptChar(); }
// --------------------------------------------------------------------------- // ^FUNCTION: Options::parse_longopt - parse a long-option // // ^SYNOPSIS: // int Options::parse_longopt(iter, optarg) // // ^PARAMETERS: // OptIter & iter -- option iterator // const char * & optarg -- where to store any option-argument // // ^DESCRIPTION: // Parse the next long-option in iter (advancing as necessary). // Make sure we update the nextchar pointer along the way. Any option // we find should be returned and optarg should point to its argument. // // ^REQUIREMENTS: // - nextchar must point to the prospective option character // // ^SIDE-EFFECTS: // - iter is advanced when an argument completely parsed // - optarg is modified to point to any option argument // - if Options::QUIET is not set, error messages are printed on cerr // // ^RETURN-VALUE: // 'c' if the the long-option corresponding to the -c option was matched // (optarg points to its argument) // BADKWD if the option is invalid (optarg points to the bad long-option // name). // // ^ALGORITHM: // It gets complicated -- follow the comments in the source. // ^^------------------------------------------------------------------------- int Options::parse_longopt(OptIter & iter, const char * & optarg) { int len = 0, ambiguous = 0; listopt = NULLSTR ; // reset the list-spec if ((optvec == NULL) || (! *optvec)) return Options::ENDOPTS; // if a value is supplied in this argv element, get it now const char * val = strpbrk(nextchar, ":=") ; if (val) { len = val - nextchar ; ++val ; } // Try to match a known long-option OptionSpec optspec = match_longopt(nextchar, len, ambiguous); // Check for an unknown long-option if (optspec.isNULL()) { // See if this was a short-option in disguise if ((! ambiguous) && (! (optctrls & Options::NOGUESSING))) { unsigned save_ctrls = optctrls; const char * save_nextchar = nextchar; optctrls |= (Options::QUIET | Options::NOGUESSING); int optchar = parse_opt(iter, optarg); optctrls = save_ctrls; if (optchar > 0) { return optchar; } else { nextchar = save_nextchar; } } if (! (optctrls & Options::QUIET)) { cerr << cmdname << ": " << ((ambiguous) ? "ambiguous" : "unknown") << " option " << ((optctrls & Options::LONG_ONLY) ? "-" : "--") << nextchar << "." << endl ; } optarg = nextchar; // record the bad option in optarg nextchar = NULLSTR; // we've exhausted this argument return (ambiguous) ? Options::AMBIGUOUS : Options::BADKWD; } // If no argument is taken, then leave now if (optspec.isNoArg()) { if ((val) && ! (optctrls & Options::QUIET)) { cerr << cmdname << ": option " << ((optctrls & Options::LONG_ONLY) ? "-" : "--") << optspec.LongOpt() << " does NOT take an argument." << endl ; } optarg = val; // record the unexpected argument nextchar = NULLSTR; // we've exhausted this argument return optspec.OptChar(); } // Check for argument in this arg if (val) { optarg = val; // the argument is right here nextchar = NULLSTR; // we exhausted the rest of this arg if (optspec.isList()) listopt = optspec ; // save the list-spec return optspec.OptChar(); } // Check for argument in next arg const char * nextarg = iter.curr(); // find the next argument to parse if ((nextarg != NULL) && (optspec.isValRequired() || (! isOption(optctrls, nextarg)))) { optarg = nextarg; // the argument is right here iter.next(); // end of arg - advance nextchar = NULLSTR; // we exhausted the rest of this arg if (optspec.isList()) listopt = optspec ; // save the list-spec return optspec.OptChar(); } // No argument given - if its required, thats an error optarg = NULLSTR; if (optspec.isValRequired() && !(optctrls & Options::QUIET)) { const char * longopt = optspec.LongOpt(); const char * spc = ::strchr(longopt, ' '); int longopt_len; if (spc) { longopt_len = spc - longopt; } else { longopt_len = ::strlen(longopt); } cerr << cmdname << ": argument required for " << ((optctrls & Options::LONG_ONLY) ? "-" : "--"); cerr.write(longopt, longopt_len) << " option." << endl ; } nextchar = NULLSTR; // we exhausted the rest of this arg return optspec.OptChar(); }