c/c++参数解析
来源:互联网 发布:win10平板安装ubuntu 编辑:程序博客网 时间:2024/05/22 13:27
#include <algorithm>#include <string>#include <iostream>using namespace std;//For example, to read the name of a file after a -f command line argument. You can also just detect if a single-word option has been passed in like -h for help.char* getCmdOption(char ** begin, char ** end, const std::string & option){char ** itr = std::find(begin, end, option);if (itr != end && ++itr != end){return *itr;}return 0;}bool cmdOptionExists(char** begin, char** end, const std::string& option){return std::find(begin, end, option) != end;}int main(int argc, char * argv[]){if(cmdOptionExists(argv, argv+argc, "-h")){char * h_info = getCmdOption(argv, argv + argc, "-h");cout<<h_info<<endl;}char * filename = getCmdOption(argv, argv + argc, "-f");if (filename){cout<<filename<<endl;}return 0;}
#include <stdio.h>#include <string.h>#include <stdlib.h>int main(int argc, char** argv) {char* filename;int convergence;int accuracy;double targetBitRate;int frameRate;int i=0;for (i = 1; i < argc; i++) {if (strcmp(argv[i],"-i")==0) {filename = argv[i+1];printf("filename: %s",filename);} else if (strcmp(argv[i],"-c")==0) {convergence = atoi(argv[i + 1]);printf("\nconvergence: %d",convergence);} else if (strcmp(argv[i],"-a")==0) {accuracy = atoi(argv[i + 1]);printf("\naccuracy:%d",accuracy);} else if (strcmp(argv[i],"-t")==0) {targetBitRate = atof(argv[i + 1]);printf("\ntargetBitRate:%f",targetBitRate);} else if (strcmp(argv[i],"-f")==0) {frameRate = atoi(argv[i + 1]);printf("\nframeRate:%d",frameRate);}}return 0;}
#include <string.h>#include <stdio.h>typedef int BOOL;#define TRUE 1#define FALSE 0//For example, to read the name of a file after a -f command line argument. You can also just detect if a single-word option has been passed in like -h for help.char* getCmdOption(int argc,char * argv[], char* option){int i=0;char * cmd={0};for (i=0;i<argc;i++){if(strcmp(argv[i],option)==0){if(i<argc-1){cmd=argv[i+1];}break;}}return cmd;}BOOL cmdOptionExists(int argc,char * argv[], char* option){int i=0;BOOL isExist=FALSE;for (i=0;i<argc;i++){if(strcmp(argv[i],option)==0){isExist=TRUE;break;}}return isExist;}int main(int argc, char * argv[]){char * filename={0};if(cmdOptionExists(argc,argv, "-h")){char * h_info = getCmdOption(argc,argv,"-h");if(h_info){printf("%s\n",h_info);}}filename= getCmdOption(argc,argv,"-f");if (filename){printf("%s\n",filename);}return 0;}
http://stackoverflow.com/questions/865668/parse-command-line-arguments
#include <cstdlib> #include <iostream> #include <string> #include <boost/program_options.hpp>using namespace std;namespace po = boost::program_options;//dd.exe --help jj --compression 5//dd.exe --compression 5int main( int argc, char* argv[] ){// Declare the supported options.po::options_description desc("Allowed options");desc.add_options()("help", "produce help message 帮助信息")("compression", po::value<int>(), "set compression level 编译级别");po::variables_map vm;po::store(po::parse_command_line(argc, argv, desc), vm);po::notify(vm); if (vm.count("help")) {cout << desc << "\n";return 1;}if (vm.count("compression")) {cout << "Compression level was set to " << vm["compression"].as<int>() << ".\n";} else {cout << "Compression level was not set.\n";}return 0;}
carg_parser.h
/* Arg_parser - POSIX/GNU command line argument parser. (C version) Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013 Antonio Diaz Diaz. This library is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this library. If not, see <http://www.gnu.org/licenses/>. As a special exception, you may use this file as part of a free software library without restriction. Specifically, if other files instantiate templates or use macros or inline functions from this file, or you compile this file and link it with other files to produce an executable, this file does not by itself cause the resulting executable to be covered by the GNU General Public License. This exception does not however invalidate any other reasons why the executable file might be covered by the GNU General Public License.*//* Arg_parser reads the arguments in 'argv' and creates a number of option codes, option arguments and non-option arguments. In case of error, 'ap_error' returns a non-null pointer to an error message. 'options' is an array of 'struct ap_Option' terminated by an element containing a code which is zero. A null name means a short-only option. A code value outside the unsigned char range means a long-only option. Arg_parser normally makes it appear as if all the option arguments were specified before all the non-option arguments for the purposes of parsing, even if the user of your program intermixed option and non-option arguments. If you want the arguments in the exact order the user typed them, call 'ap_init' with 'in_order' = true. The argument '--' terminates all options; any following arguments are treated as non-option arguments, even if they begin with a hyphen. The syntax for optional option arguments is '-<short_option><argument>' (without whitespace), or '--<long_option>=<argument>'.*/#ifdef __cplusplusextern "C" {#endifenum ap_Has_arg { ap_no, ap_yes, ap_maybe };struct ap_Option { int code;/* Short option letter or code ( code != 0 ) */ const char * name;/* Long option name (maybe null) */ enum ap_Has_arg has_arg; };struct ap_Record { int code; char * argument; };struct Arg_parser { struct ap_Record * data; char * error; int data_size; int error_size; };char ap_init( struct Arg_parser * const ap, const int argc, const char * const argv[], const struct ap_Option options[], const char in_order );void ap_free( struct Arg_parser * const ap );const char * ap_error( const struct Arg_parser * const ap ); /* The number of arguments parsed (may be different from argc) */int ap_arguments( const struct Arg_parser * const ap ); /* If ap_code( i ) is 0, ap_argument( i ) is a non-option. Else ap_argument( i ) is the option's argument (or empty). */int ap_code( const struct Arg_parser * const ap, const int i );const char * ap_argument( const struct Arg_parser * const ap, const int i );#ifdef __cplusplus}#endifcarg_parser.c
/* Arg_parser - POSIX/GNU command line argument parser. (C version)Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013Antonio Diaz Diaz.This library is free software: you can redistribute it and/or modifyit under the terms of the GNU General Public License as published bythe Free Software Foundation, either version 3 of the License, or(at your option) any later version.This library is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; without even the implied warranty ofMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See theGNU General Public License for more details.You should have received a copy of the GNU General Public Licensealong with this library. If not, see <http://www.gnu.org/licenses/>.As a special exception, you may use this file as part of a freesoftware library without restriction. Specifically, if other filesinstantiate templates or use macros or inline functions from thisfile, or you compile this file and link it with other files toproduce an executable, this file does not by itself cause theresulting executable to be covered by the GNU General PublicLicense. This exception does not however invalidate any otherreasons why the executable file might be covered by the GNU GeneralPublic License.*/#include <stdlib.h>#include <string.h>#include "carg_parser.h"/* assure at least a minimum size for buffer 'buf' */static void * ap_resize_buffer( void * buf, const int min_size ){if( buf ) buf = realloc( buf, min_size );else buf = malloc( min_size );return buf;}static char push_back_record( struct Arg_parser * const ap,const int code, const char * const argument ){const int len = strlen( argument );struct ap_Record *p;void * tmp = ap_resize_buffer( ap->data,( ap->data_size + 1 ) * sizeof (struct ap_Record) );if( !tmp ) return 0;ap->data = (struct ap_Record *)tmp;p = &(ap->data[ap->data_size]);p->code = code;p->argument = 0;tmp = ap_resize_buffer( p->argument, len + 1 );if( !tmp ) return 0;p->argument = (char *)tmp;strncpy( p->argument, argument, len + 1 );++ap->data_size;return 1;}static char add_error( struct Arg_parser * const ap, const char * const msg ){const int len = strlen( msg );void * tmp = ap_resize_buffer( ap->error, ap->error_size + len + 1 );if( !tmp ) return 0;ap->error = (char *)tmp;strncpy( ap->error + ap->error_size, msg, len + 1 );ap->error_size += len;return 1;}static void free_data( struct Arg_parser * const ap ){int i;for( i = 0; i < ap->data_size; ++i ) free( ap->data[i].argument );if( ap->data ) { free( ap->data ); ap->data = 0; }ap->data_size = 0;}static char parse_long_option( struct Arg_parser * const ap,const char * const opt, const char * const arg,const struct ap_Option options[],int * const argindp ){unsigned len;int index = -1, i;char exact = 0, ambig = 0;for( len = 0; opt[len+2] && opt[len+2] != '='; ++len ) ;/* Test all long options for either exact match or abbreviated matches. */for( i = 0; options[i].code != 0; ++i )if( options[i].name && strncmp( options[i].name, &opt[2], len ) == 0 ){if( strlen( options[i].name ) == len )/* Exact match found */{ index = i; exact = 1; break; }else if( index < 0 ) index = i;/* First nonexact match found */else if( options[index].code != options[i].code ||options[index].has_arg != options[i].has_arg )ambig = 1;/* Second or later nonexact match found */}if( ambig && !exact ){add_error( ap, "option '" ); add_error( ap, opt );add_error( ap, "' is ambiguous" );return 1;}if( index < 0 )/* nothing found */{add_error( ap, "unrecognized option '" ); add_error( ap, opt );add_error( ap, "'" );return 1;}++*argindp;if( opt[len+2] )/* '--<long_option>=<argument>' syntax */{if( options[index].has_arg == ap_no ){add_error( ap, "option '--" ); add_error( ap, options[index].name );add_error( ap, "' doesn't allow an argument" );return 1;}if( options[index].has_arg == ap_yes && !opt[len+3] ){add_error( ap, "option '--" ); add_error( ap, options[index].name );add_error( ap, "' requires an argument" );return 1;}return push_back_record( ap, options[index].code, &opt[len+3] );}if( options[index].has_arg == ap_yes ){if( !arg || !arg[0] ){add_error( ap, "option '--" ); add_error( ap, options[index].name );add_error( ap, "' requires an argument" );return 1;}++*argindp;return push_back_record( ap, options[index].code, arg );}return push_back_record( ap, options[index].code, "" );}static char parse_short_option( struct Arg_parser * const ap,const char * const opt, const char * const arg,const struct ap_Option options[],int * const argindp ){int cind = 1;/* character index in opt */while( cind > 0 ){int index = -1, i;const unsigned char code = opt[cind];char code_str[2];code_str[0] = code; code_str[1] = 0;if( code != 0 )for( i = 0; options[i].code; ++i )if( code == options[i].code ){ index = i; break; }if( index < 0 ){add_error( ap, "invalid option -- " ); add_error( ap, code_str );return 1;}if( opt[++cind] == 0 ) { ++*argindp; cind = 0; }/* opt finished */if( options[index].has_arg != ap_no && cind > 0 && opt[cind] ){if( !push_back_record( ap, code, &opt[cind] ) ) return 0;++*argindp; cind = 0;}else if( options[index].has_arg == ap_yes ){if( !arg || !arg[0] ){add_error( ap, "option requires an argument -- " );add_error( ap, code_str );return 1;}++*argindp; cind = 0;if( !push_back_record( ap, code, arg ) ) return 0;}else if( !push_back_record( ap, code, "" ) ) return 0;}return 1;}char ap_init( struct Arg_parser * const ap,const int argc, const char * const argv[],const struct ap_Option options[], const char in_order ){const char ** non_options = 0;/* skipped non-options */int non_options_size = 0;/* number of skipped non-options */int argind = 1;/* index in argv */int i;ap->data = 0;ap->error = 0;ap->data_size = 0;ap->error_size = 0;if( argc < 2 || !argv || !options ) return 1;while( argind < argc ){const unsigned char ch1 = argv[argind][0];const unsigned char ch2 = ( ch1 ? argv[argind][1] : 0 );if( ch1 == '-' && ch2 )/* we found an option */{const char * const opt = argv[argind];const char * const arg = (argind + 1 < argc) ? argv[argind+1] : 0;if( ch2 == '-' ){if( !argv[argind][2] ) { ++argind; break; }/* we found "--" */else if( !parse_long_option( ap, opt, arg, options, &argind ) ) return 0;}else if( !parse_short_option( ap, opt, arg, options, &argind ) ) return 0;if( ap->error ) break;}else{if( !in_order ){void * tmp = ap_resize_buffer( non_options,( non_options_size + 1 ) * sizeof *non_options );if( !tmp ) return 0;non_options = (const char **)tmp;non_options[non_options_size++] = argv[argind++];}else if( !push_back_record( ap, 0, argv[argind++] ) ) return 0;}}if( ap->error ) free_data( ap );else{for( i = 0; i < non_options_size; ++i )if( !push_back_record( ap, 0, non_options[i] ) ) return 0;while( argind < argc )if( !push_back_record( ap, 0, argv[argind++] ) ) return 0;}if( non_options ) free( non_options );return 1;}void ap_free( struct Arg_parser * const ap ){free_data( ap );if( ap->error ) { free( ap->error ); ap->error = 0; }ap->error_size = 0;}const char * ap_error( const struct Arg_parser * const ap ){ return ap->error; }int ap_arguments( const struct Arg_parser * const ap ){ return ap->data_size; }int ap_code( const struct Arg_parser * const ap, const int i ){if( i >= 0 && i < ap_arguments( ap ) ) return ap->data[i].code;else return 0;}const char * ap_argument( const struct Arg_parser * const ap, const int i ){if( i >= 0 && i < ap_arguments( ap ) ) return ap->data[i].argument;else return "";}
/* Arg_parser - POSIX/GNU command line argument parser. (C version)Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013Antonio Diaz Diaz.This program is free software: you can redistribute it and/or modifyit under the terms of the GNU General Public License as published bythe Free Software Foundation, either version 3 of the License, or(at your option) any later version.This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; without even the implied warranty ofMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See theGNU General Public License for more details.You should have received a copy of the GNU General Public Licensealong with this program. If not, see <http://www.gnu.org/licenses/>.*//*Return values: 0 for a normal exit, 1 for environmental problems(file not found, invalid flags, I/O errors, etc), 2 to indicate acorrupt or invalid input file, 3 for an internal consistency error(eg, bug) which caused arg_parser to panic.*/#include <stdio.h>#include <stdlib.h>#include <string.h>#include "carg_parser.h"static const char * const Program_name = "Arg_parser";static const char * const program_name = "arg_parser";static const char * const program_year = "2013";static const char * invocation_name = 0;#define PROGVERSION "arg_parser_1.8"void show_help( const char verbose ){printf( "%s - POSIX/GNU command line argument parser. (C version)\n", Program_name );printf( "See the source file 'cmain.c' to learn how to use %s in\n", Program_name );printf( "your own programs.\n""\nUsage: %s [options]\n", invocation_name );printf( "\nOptions:\n"" -h, --help display this help and exit\n"" -V, --version output version information and exit\n"" -a, --append example of option with no argument\n"" -b, --block=<arg> example of option with required argument\n"" -c, --casual[=<arg>] example of option with optional argument\n"" -o <arg> example of short only option\n"" --orphan example of long only option\n"" -q, --quiet quiet operation\n"" -u, --uncaught example of intentional bug\n"" -v, --verbose verbose operation\n" );if( verbose ){printf( " -H, --hidden example of hidden option (shown with -v -h)\n" );}printf( "\nReport bugs to bug-moe@gnu.org\n""Arg_parser home page: http://www.nongnu.org/arg-parser/arg_parser.html\n" );}void show_version(){printf( "%s %s\n", Program_name, PROGVERSION );printf( "Copyright (C) %s Antonio Diaz Diaz.\n", program_year );printf( "License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>\n""This is free software: you are free to change and redistribute it.\n""There is NO WARRANTY, to the extent permitted by law.\n" );}void show_error( const char * const msg, const int errcode, const char help ){if( msg && msg[0] ){fprintf( stderr, "%s: %s", program_name, msg );if( errcode > 0 )fprintf( stderr, ": %s", strerror( errcode ) );fprintf( stderr, "\n" );}if( help )fprintf( stderr, "Try '%s --help' for more information.\n",invocation_name );}void internal_error( const char * const msg ){fprintf( stderr, "%s: internal error: %s.\n", program_name, msg );exit( 3 );}const char * optname( const int code, const struct ap_Option options[] ){static char buf[2] = "?";int i;if( code != 0 )for( i = 0; options[i].code; ++i )if( code == options[i].code ){ if( options[i].name ) return options[i].name; else break; }if( code > 0 && code < 256 ) buf[0] = code; else buf[0] = '?';return buf;}//arg_parser.exe -H -a -V//http://download.savannah.gnu.org/releases/arg-parser/int main( const int argc, const char * const argv[] ){char verbose = 0;const struct ap_Option options[] ={{ 'H', "hidden", ap_no },{ 'V', "version", ap_no },{ 'a', "append", ap_no },{ 'b', "block", ap_yes },{ 'c', "casual", ap_maybe },{ 'h', "help", ap_no },{ 'o', 0, ap_yes },{ 'q', "quiet", ap_no },{ 'u', "uncaught", ap_no },{ 'v', "verbose", ap_no },{ 256, "orphan", ap_no },{ 0, 0, ap_no } };struct Arg_parser parser;int argind;invocation_name = argv[0];if( !ap_init( &parser, argc, argv, options, 0 ) ){ show_error( "Memory exhausted.", 0, 0 ); return 1; }if( ap_error( &parser ) )/* bad option */{ show_error( ap_error( &parser ), 0, 1 ); return 1; }for( argind = 0; argind < ap_arguments( &parser ); ++argind ){const int code = ap_code( &parser, argind );if( !code ) break;/* no more options */switch( code ){case 'H': break;/* example, do nothing */case 'V': show_version(); return 0;case 'a': break;/* example, do nothing */case 'b': break;/* example, do nothing */case 'c': break;/* example, do nothing */case 'h': show_help( verbose ); return 0;case 'o': break;/* example, do nothing */case 'q': verbose = 0; break;/* case 'u': break; *//* intentionally not caught */case 'v': verbose = 1; break;case 256: break;/* example, do nothing */default : internal_error( "uncaught option" );}} /* end process options */for( argind = 0; argind < ap_arguments( &parser ); ++argind ){const int code = ap_code( &parser, argind );const char * const arg = ap_argument( &parser, argind );if( code )/* option */{const char * const name = optname( code, options );if( !name[1] )printf( "option '-%c'", name[0] );elseprintf( "option '--%s'", name );if( arg[0] )printf( " with argument '%s'", arg );}else/* non-option */printf( "non-option argument '%s'", arg );printf( "\n" );}if( !ap_arguments( &parser ) ) printf( "Hello, world!\n" );return 0;}
0 0
- c/c++参数解析
- C/C++命令行参数解析
- C语言可变参数解析
- C语言解析命令行参数
- C 不定参数精要解析
- C语言-解析命令行参数
- 深入解析C语言变长参数列表
- C参数指针-常见错误解析
- Linux C编程--main函数参数解析
- Linux c 汇编语言参数传递解析
- Linux C编程--main函数参数解析 .
- Linux C编程 main函数参数解析
- Linux C解析控制台输入命令行参数
- object c 多参数函数解析
- c的Main函数参数解析
- 【C#】ToString()参数中格式解析大全
- Linux C编程--main函数参数解析
- [华为OJ--C++]048-参数解析
- Java API接口调用,返回json格式处理
- 设计模式 装饰者模式 带你重回传奇世界
- JavaScript学习第一天
- Linux vmstat命令实战详解
- java技术的学习提高,从“就这样用”到“为什么这样用”(一)
- c/c++参数解析
- Embedded statement cannot be a declaration or labeled statement
- (4.1.2.1)基础总结篇之二:Activity的四种launchMode
- 【重温经典】张小龙:微信背后的产品观
- 设计模式 工厂模式 从卖肉夹馍说起
- C# 不安装oracle客户端使用DLL连接数据库,初始化类型错误
- 在VI中删除行尾的换行符
- Linux下配置php开发环境
- iOS 预留帖子。