linux 使用getopt_long()从命令行获取参数,struct option

Linux中getopt_long()函数 getopt_long()是在 Linux(以及其他类 UNIX 系统)编程中用于解析命令行选项的函数。它是getopt()函数的扩展版本,getopt()主要用于处理短选项(例如-a、-b等),而getopt_long()可以同时处理短选项和长选项(例如--help、--version等) 阅读详情

函数说明

#include
函数说明:
函数getopt用来解析命令行参数。
函数getopt_long支持长选项的命令行解析。

函数原型:
intgetopt_long(int argc, char* constargv[], 
                     const char*optstring,
                     const struct option*longopts, 
                     int*longindex);
参数:
argc、argv直接从main函数中获取。
opting是选项参数组成的字符串,由下列元素组成:
1.单个字符,表示选项,
2.单个字符后接一个冒号:表示该选项后必须跟一个参数。参数紧跟在选项后或者以空格隔开。该参数的指针赋给optarg。
3.单个字符后跟两个冒号,表示该选项后可以有参数也可以没有参数。如果有参数,参数必须紧跟在选项后不能以空格隔开。该参数的指针赋给optarg。(这个特性是GNU的扩张)。
optstring是一个字符串,表示可以接受的参数。例如,"a:b:cd",表示可以接受的参数是a,b,c,d,其中,a和b参数后面跟有更多的参数值。(例如:-ahost -b name)
longopts是一个结构的实例:
structoption
{
   constchar *name; //name表示的是长参数名
   inthas_arg; //has_arg有3个值,no_argument(或者是0),表示该参数后面不跟参数值
              //required_argument(或者是1),表示该参数后面一定要跟个参数值
              //optional_argument(或者是2),表示该参数后面可以跟,也可以不跟参数值
   int*flag;    //用来决定getopt_long()的返回值是什么。
              //flag是null,则函数会返回与该项option匹配的val值。
   int val;     //和flag联合决定返回值
 };
int *flag 如果这个指针为NULL,那么getopt_long()返回该结构val字段中的数值。如果该指针不NULL,getopt_long()会使得它所指向的变量中填入val字段中的数值,并且getopt_long()返回0。如果flag不是NULL,但未发现长选项,那么它所指向的变量的数值不变。
int val 这个值是发现了长选项时的返回值,或者flag不是NULL时载入*flag中的值。典型情况下,若flag不是NULL,那么val是个真/假值,譬如1或0;另一方面,如果flag是NULL,那么val通常是字符常量,若长选项与短选项一致,那么该字符常量应该与optstring中出现的这个选项的参数相同。
=========================================================================
给个例子:
struct option long_options[] ={
          {"a123", required_argument,0, 'a'},
          {"c123", no_argument, 0,'c'},
};
现在,如果命令行的参数是-a123,那么调用getopt_long()将返回字符'a',并且将字符串123由 optarg返回( 注意注意!字符串123由optarg带回!optarg不需要定义,在getopt.h中已经有定义)。
那么,如果命令行参数是-c,那么调用getopt_long()将返回字符'c',而此时,optarg是null。
最后,当getopt_long()将命令行所有参数全部解析完成后,返回-1。
===========================================================================
以上来自网络,便于学习记忆摘录在这里,下面是自己的理解:
函数原型: int getopt_long(intargc, char* const argv[], 
                     const char*optstring,
                     const struct option*longopts, 
                     int*longindex);
其中 optstring为单个字符参数,称为short_opts。
而longopts为多个字符(即一个或多个单词连接)参数,称为long_opts。
参数longindex为longopts数组中的索引返回值。
具体用法参考suricata中main()函数中解析命令行参数:
//短字符参数
charshort_opts[] = "c:TDhi:l:q:d:r:us:S:U:VF:";

//长字符参数
 structoption long_opts[] = {
       {"dump-config", 0, &dump_config, 1},  //  getopt_long 返回值为0, dump_config保存为1
       {"pfring", optional_argument, 0, 0},  //  getopt_long 返回值为0
       {"pfring-int", required_argument, 0, 0}, //  getopt_long 返回值为0,必须有参数
       {"pfring-cluster-id", required_argument, 0,0},
       {"pfring-cluster-type", required_argument, 0,0},
       {"af-packet", optional_argument, 0, 0},
       {"pcap", optional_argument, 0, 0},
       {"pcap-buffer-size", required_argument, 0,0},
       {"unittest-filter", required_argument, 0,'U'}, //  getopt_long 返回值为‘U’,必须有参数
       {"list-app-layer-protos", 0,&list_app_layer_protocols, 1},
       {"list-unittests", 0, &list_unittests,1},
       {"list-cuda-cards", 0, &list_cuda_cards,1},
       {"list-runmodes", 0, &list_runmodes,1},
       {"list-keywords", optional_argument,&list_keywords, 1},
       {"runmode", required_argument, NULL, 0},
       {"engine-analysis", 0, &engine_analysis,1},
       {"pidfile", required_argument, 0, 0},
       {"init-errors-fatal", 0, 0, 0},
       {"fatal-unittests", 0, 0, 0},
       {"user", required_argument, 0, 0},
       {"group", required_argument, 0, 0},
       {"erf-in", required_argument, 0, 0},
       {"dag", required_argument, 0, 0},
       {"napatech", 0, 0, 0},
       {"build-info", 0, &build_info, 1},
       {NULL, 0, NULL, 0}
    };
   // 长字符数组索引
    intoption_index = 0;
 
 // 以下是用法  
 while ((opt= getopt_long(argc, argv, short_opts, long_opts,&option_index)) != -1) 
 {
       switch (opt) 
       {      // case为函数返回值
        case 0:
          if(strcmp((long_opts[option_index]).name , "pfring") == 0 ||                                 strcmp((long_opts[option_index]).name , "pfring-int") ==0) 
          {
            // TO-DO...
          }
           else if(strcmp((long_opts[option_index]).name , "pcap") ==0) 
          {
            // TO-DO...
          }
          break;
        case 'c':
          break; 
        case 'T':
          break;
        default:
          usage(argv[0]); 
          exit(EXIT_FAILURE);
       }
 }

函数使用

众所周知,C程序的主函数有两个参数,其中,第一个参数是整型,可以获得包括程序名字的参数个数,第二个参数是字符数组指针或字符指针的指针,可以按顺序获得命令行上各个字符串参数。其原形是:

int main(int argc, char *argv[]);

或者

int main(int argc, char **argv);

 

如果有一个解析CDR的程序,名叫destroy,负责将一个二进制格式的CDR文件转换为文本文件,输出的文本的样式由另外一个描述文件定义,那么,命令行要求输入的参数就有三个:CDR文件名、输出文件名和描述文件名。其中,前两个参数是必须输入的,第三个的描述文件名可以不输入,程序会自动采用默认的输出样式。很自然,主函数的三个参数就应该这样排列:

./destroy cdr cdr.txt [cdr.desc]

 

这样做在一般情况下不会有太大问题,问题来源于扩展性的需求。如果有一天,用户要求解析程序能够按关键字解析,只有含有关键字的CDR才能够输出。解决方法很简单,只要在参数列表的最后,加上它就可以了。不过,这样就使得原本可选的描述文件名变为必须输入:

./destroy cdr cdr.txt cdr.desc [keyword]

 

因为不改的话,你就不知道,第三个参数究竟是描述文件名,还是关键字。现在还算好办,如果以后陆续有增加参数的需求,关键字也变成必须输入了,这个时候,如果要查找全部CDR,你还得定义一个“特殊的关键字”,告诉程序,把数据统统给我捞出来……

 

有鉴于此,在Unix/Linux的正式的项目上,程序员通常会使用getopt()或者getopt_long()来获得输入的参数。两者的一个区别在于getopt()只支持短格式参数,而getopt_long()既支持短格式参数,又支持长格式参数。

短格式:./destroy -f cdr -o cdr.txt -c cdr.desc -k 123456

长格式:./destroy --file cdr --output cdr.txt --config cdr.desc --keyword 123456

 

引入了getopt()和getopt_long()的项目,设计者可以按需要,方便地增加参数,或者随意地放置参数的先后次序,只需要在程序中判断,哪些参数是必须的就可以了。关于这两个函数的用法,大家可以上网搜索一下,不再累述。附件destroy_linux.c给出了在Linux下使用getopt_long()的实例。

[cpp]  view plain copy
  1. #include <stdio.h>  
  2. #include <stdlib.h>  
  3. #include <unistd.h>  
  4. #include <getopt.h>  
  5.   
  6. void print_usage(const char *program_name) {  
  7.     printf("%s 1.0.0 (2010-06-13)/n", program_name);  
  8.     printf("This is a program decoding a BER encoded CDR file/n");  
  9.     printf("Usage: %s -f <file_name> -o <output_name> [-c <config_name>] [-k <keyword>]/n", program_name);  
  10.     printf("    -f --file       the CDR file to be decoded/n");  
  11.     printf("    -o --output     the output file in plain text format/n");  
  12.     printf("    -c --config     the description file of the CDR file, if not given, use default configuration/n");  
  13.     printf("    -k --keyword    the keyword to search, if not given, all records will be written into output file/n");  
  14. }  
  15.   
  16. int main(int argc, char *argv[]) {  
  17.     char *file_name = NULL;  
  18.     char *output_name = NULL;  
  19.     char *config_name = NULL;  
  20.     char *keyword = NULL;  
  21.   
  22.     const char *short_opts = "hf:o:c:k:";  
  23.     const struct option long_opts[] = {  
  24.         {"help", no_argument, NULL, 'h'},  
  25.         {"file", required_argument, NULL, 'f'},  
  26.         {"output", required_argument, NULL, 'o'},  
  27.         {"config", required_argument, NULL, 'c'},  
  28.         {"keyword", required_argument, NULL, 'k'},  
  29.         {0, 0, 0, 0}  
  30.     };  
  31.     int hflag = 0;  
  32.   
  33.     int c;  
  34.     opterr = 0;  
  35.   
  36.     while ( (c = getopt_long(argc, argv, short_opts, long_opts, NULL)) != -1 ) {  
  37.         switch ( c ) {  
  38.             case 'h' :  
  39.                 hflag = 1;  
  40.                 break;  
  41.             case 'f' :  
  42.                 file_name = optarg;  
  43.                 break;  
  44.             case 'o' :  
  45.                 output_name = optarg;  
  46.                 break;  
  47.             case 'c' :  
  48.                 config_name = optarg;  
  49.                 break;  
  50.             case 'k' :  
  51.                 keyword = optarg;  
  52.                 break;  
  53.             case '?' :  
  54.                 if ( optopt == 'f' || optopt == 'o' || optopt == 'c' || optopt == 'k' )  
  55.                     printf("Error: option -%c requires an argument/n", optopt);  
  56.                 else if ( isprint(optopt) )  
  57.                     printf("Error: unknown option '-%c'/n", optopt);  
  58.                 else  
  59.                     printf("Error: unknown option character '//x%x'/n", optopt);  
  60.                 return 1;  
  61.             default :  
  62.                 abort();  
  63.         }  
  64.     }  
  65.   
  66.     if ( hflag || argc == 1 ) {  
  67.         print_usage(argv[0]);  
  68.         return 0;  
  69.     }  
  70.     if ( !file_name ) {  
  71.         printf("Error: file name must be specified/n");  
  72.         return 1;  
  73.     }  
  74.     if ( !output_name ) {  
  75.         printf("Error: output name must be specified/n");  
  76.         return 1;  
  77.     }  
  78.   
  79.     // if not setting default, Linux OK, but SunOS core dump  
  80.     if ( !config_name ) config_name = "(null)";  
  81.     if ( !keyword ) keyword = "(null)";  
  82.     printf("Parameters got: file_name = %s, output_name = %s, config_name = %s, keyword = %s/n", file_name, output_name, config_name, keyword);  
  83.     return 0;  
  84. }  

 

另外一个区别是,getopt()几乎通用于所有类Unix系统,而getopt_long()只有在GNU的Unix/Linux下才能用。如果把上述程序放到Tru64上编译,就会出现以下错误:

cc -o destroy destroy_linux.c

cc: Error: destroy_linux.c, line 24: In the initializer for long_opts, an array's element type is incomplete, which precludes its initialization. (incompelinit)

                {"help", no_argument, NULL, 'h'},

----------------^

 

所以,如果一定要在Tru64等非GNU的OS上做到长格式的效果,除了自己另起炉灶之外,基本上只好借助一些跨平台的开源项目了。附件里的getopt_long.c和getopt.h是从opensolaris的网站上抄下来的,是包含在sg3_utils软件包中的程序。sg3_utils具体是什么,我也不知道,据说是一个Linux的开发包,用来直接使用SCSI命令集访问设备。(sg3_utils is a package of utilities for accessing devices that use SCSI command sets.)反正拿来能用就是了!

[cpp]  view plain copy
  1. /*  $NetBSD: getopt.h,v 1.7 2005/02/03 04:39:32 perry Exp $ */  
  2.   
  3. /*- 
  4.  * Copyright (c) 2000 The NetBSD Foundation, Inc. 
  5.  * All rights reserved. 
  6.  * 
  7.  * This code is derived from software contributed to The NetBSD Foundation 
  8.  * by Dieter Baron and Thomas Klausner. 
  9.  * 
  10.  * Redistribution and use in source and binary forms, with or without 
  11.  * modification, are permitted provided that the following conditions 
  12.  * are met: 
  13.  * 1. Redistributions of source code must retain the above copyright 
  14.  *    notice, this list of conditions and the following disclaimer. 
  15.  * 2. Redistributions in binary form must reproduce the above copyright 
  16.  *    notice, this list of conditions and the following disclaimer in the 
  17.  *    documentation and/or other materials provided with the distribution. 
  18.  * 3. All advertising materials mentioning features or use of this software 
  19.  *    must display the following acknowledgement: 
  20.  *        This product includes software developed by the NetBSD 
  21.  *        Foundation, Inc. and its contributors. 
  22.  * 4. Neither the name of The NetBSD Foundation nor the names of its 
  23.  *    contributors may be used to endorse or promote products derived 
  24.  *    from this software without specific prior written permission. 
  25.  * 
  26.  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS 
  27.  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED 
  28.  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 
  29.  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS 
  30.  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 
  31.  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 
  32.  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 
  33.  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
  34.  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
  35.  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
  36.  * POSSIBILITY OF SUCH DAMAGE. 
  37.  */  
  38.   
  39. /* 
  40.  * modified May 12, 2005 by Jim Basney <jbasney@ncsa.uiuc.edu> 
  41.  * 
  42.  * removed #include of non-POSIX <sys/cdefs.h> and <sys/featuretest.h> 
  43.  * removed references to _NETBSD_SOURCE and HAVE_NBTOOL_CONFIG_H 
  44.  * added #if !HAVE_GETOPT_LONG 
  45.  * removed __BEGIN_DECLS and __END_DECLS 
  46.  */  
  47.   
  48. #ifndef _MYPROXY_GETOPT_H_  
  49. #define _MYPROXY_GETOPT_H_  
  50.   
  51. #if !HAVE_GETOPT_LONG  
  52.   
  53. #include <unistd.h>  
  54.   
  55. /* 
  56.  * Gnu like getopt_long() and BSD4.4 getsubopt()/optreset extensions 
  57.  */  
  58. #define no_argument        0  
  59. #define required_argument  1  
  60. #define optional_argument  2  
  61.   
  62. extern char *optarg;  
  63. extern int optind;  
  64. extern int optopt;  
  65. extern int opterr;  
  66.   
  67. struct option {  
  68.     /* name of long option */  
  69.     const char *name;  
  70.     /* 
  71.      * one of no_argument, required_argument, and optional_argument: 
  72.      * whether option takes an argument 
  73.      */  
  74.     int has_arg;  
  75.     /* if not NULL, set *flag to val when option found */  
  76.     int *flag;  
  77.     /* if flag not NULL, value to set *flag to; else return value */  
  78.     int val;  
  79. };  
  80.   
  81. int getopt_long(int, char * const *, const char *,  
  82.     const struct option *, int *);  
  83.    
  84. #endif /* !HAVE_GETOPT_LONG */  
  85.   
  86. #endif /* !_MYPROXY_GETOPT_H_ */  
[cpp]  view plain copy
  1. /*  $NetBSD: getopt_long.c,v 1.17 2004/06/20 22:20:15 jmc Exp $ */  
  2.   
  3. /*- 
  4.  * Copyright (c) 2000 The NetBSD Foundation, Inc. 
  5.  * All rights reserved. 
  6.  * 
  7.  * This code is derived from software contributed to The NetBSD Foundation 
  8.  * by Dieter Baron and Thomas Klausner. 
  9.  * 
  10.  * Redistribution and use in source and binary forms, with or without 
  11.  * modification, are permitted provided that the following conditions 
  12.  * are met: 
  13.  * 1. Redistributions of source code must retain the above copyright 
  14.  *    notice, this list of conditions and the following disclaimer. 
  15.  * 2. Redistributions in binary form must reproduce the above copyright 
  16.  *    notice, this list of conditions and the following disclaimer in the 
  17.  *    documentation and/or other materials provided with the distribution. 
  18.  * 3. All advertising materials mentioning features or use of this software 
  19.  *    must display the following acknowledgement: 
  20.  *        This product includes software developed by the NetBSD 
  21.  *        Foundation, Inc. and its contributors. 
  22.  * 4. Neither the name of The NetBSD Foundation nor the names of its 
  23.  *    contributors may be used to endorse or promote products derived 
  24.  *    from this software without specific prior written permission. 
  25.  * 
  26.  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS 
  27.  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED 
  28.  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 
  29.  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS 
  30.  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 
  31.  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 
  32.  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 
  33.  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
  34.  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
  35.  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
  36.  * POSSIBILITY OF SUCH DAMAGE. 
  37.  */  
  38.   
  39. /* 
  40.  * modified May 12, 2005 by Jim Basney <jbasney@ncsa.uiuc.edu> 
  41.  * 
  42.  * removed #include of non-POSIX <sys/cdefs.h> <err.h> 
  43.  * removed #include of "namespace.h" 
  44.  * use local "port_getopt.h" instead of <getopt.h> 
  45.  * removed REPLACE_GETOPT and HAVE_NBTOOL_CONFIG_H sections 
  46.  * removed __P() from function declarations 
  47.  * use ANSI C function parameter lists 
  48.  * removed optreset support 
  49.  * replace _DIAGASSERT() with assert() 
  50.  * replace non-POSIX warnx(...) with fprintf(stderr, ...) 
  51.  * added extern declarations for optarg, optind, opterr, and optopt 
  52.  */  
  53.   
  54. #if defined(LIBC_SCCS) && !defined(lint)  
  55. __RCSID("$NetBSD: getopt_long.c,v 1.17 2004/06/20 22:20:15 jmc Exp $");  
  56. #endif /* LIBC_SCCS and not lint */  
  57.   
  58. #include <assert.h>  
  59. #include <errno.h>  
  60. #include "getopt.h"  
  61. #include <stdio.h>  
  62. #include <stdlib.h>  
  63. #include <string.h>  
  64.   
  65. #ifdef __weak_alias  
  66. __weak_alias(getopt_long,_getopt_long)  
  67. #endif  
  68.   
  69. #if !HAVE_GETOPT_LONG  
  70. #define IGNORE_FIRST    (*options == '-' || *options == '+')  
  71. #define PRINT_ERROR ((opterr) && ((*options != ':') /  
  72.                       || (IGNORE_FIRST && options[1] != ':')))  
  73. #define IS_POSIXLY_CORRECT (getenv("POSIXLY_CORRECT") != NULL)  
  74. #define PERMUTE         (!IS_POSIXLY_CORRECT && !IGNORE_FIRST)  
  75. /* XXX: GNU ignores PC if *options == '-' */  
  76. #define IN_ORDER        (!IS_POSIXLY_CORRECT && *options == '-')  
  77.   
  78. /* return values */  
  79. #define BADCH   (int)'?'  
  80. #define BADARG      ((IGNORE_FIRST && options[1] == ':') /  
  81.              || (*options == ':') ? (int)':' : (int)'?')  
  82. #define INORDER (int)1  
  83.   
  84. #define EMSG    ""  
  85.   
  86. extern char *optarg;  
  87. extern int optind, opterr, optopt;  
  88.   
  89. static int getopt_internal (int, char * const *, const char *);  
  90. static int gcd (int, int);  
  91. static void permute_args (int, int, int, char * const *);  
  92.   
  93. static char *place = EMSG; /* option letter processing */  
  94.   
  95. static int nonopt_start = -1; /* first non option argument (for permute) */  
  96. static int nonopt_end = -1;   /* first option after non options (for permute) */  
  97.   
  98. /* Error messages */  
  99. static const char recargchar[] = "option requires an argument -- %c";  
  100. static const char recargstring[] = "option requires an argument -- %s";  
  101. static const char ambig[] = "ambiguous option -- %.*s";  
  102. static const char noarg[] = "option doesn't take an argument -- %.*s";  
  103. static const char illoptchar[] = "unknown option -- %c";  
  104. static const char illoptstring[] = "unknown option -- %s";  
  105.   
  106.   
  107. /* 
  108.  * Compute the greatest common divisor of a and b. 
  109.  */  
  110. static int  
  111. gcd(int a, int b)  
  112. {  
  113.     int c;  
  114.   
  115.     c = a % b;  
  116.     while (c != 0) {  
  117.         a = b;  
  118.         b = c;  
  119.         c = a % b;  
  120.     }  
  121.          
  122.     return b;  
  123. }  
  124.   
  125. /* 
  126.  * Exchange the block from nonopt_start to nonopt_end with the block 
  127.  * from nonopt_end to opt_end (keeping the same order of arguments 
  128.  * in each block). 
  129.  */  
  130. static void  
  131. permute_args(int panonopt_start, int panonopt_end, int opt_end,  
  132.          char * const *nargv)  
  133. {  
  134.     int cstart, cyclelen, i, j, ncycle, nnonopts, nopts, pos;  
  135.     char *swap;  
  136.   
  137.     assert(nargv != NULL);  
  138.   
  139.     /* 
  140.      * compute lengths of blocks and number and size of cycles 
  141.      */  
  142.     nnonopts = panonopt_end - panonopt_start;  
  143.     nopts = opt_end - panonopt_end;  
  144.     ncycle = gcd(nnonopts, nopts);  
  145.     cyclelen = (opt_end - panonopt_start) / ncycle;  
  146.   
  147.     for (i = 0; i < ncycle; i++) {  
  148.         cstart = panonopt_end+i;  
  149.         pos = cstart;  
  150.         for (j = 0; j < cyclelen; j++) {  
  151.             if (pos >= panonopt_end)  
  152.                 pos -= nnonopts;  
  153.             else  
  154.                 pos += nopts;  
  155.             swap = nargv[pos];  
  156.             /* LINTED const cast */  
  157.             ((char **) nargv)[pos] = nargv[cstart];  
  158.             /* LINTED const cast */  
  159.             ((char **)nargv)[cstart] = swap;  
  160.         }  
  161.     }  
  162. }  
  163.   
  164. /* 
  165.  * getopt_internal -- 
  166.  *  Parse argc/argv argument vector.  Called by user level routines. 
  167.  *  Returns -2 if -- is found (can be long option or end of options marker). 
  168.  */  
  169. static int  
  170. getopt_internal(int nargc, char * const *nargv, const char *options)  
  171. {  
  172.     char *oli;              /* option letter list index */  
  173.     int optchar;  
  174.   
  175.     assert(nargv != NULL);  
  176.     assert(options != NULL);  
  177.   
  178.     optarg = NULL;  
  179.   
  180.     /* 
  181.      * XXX Some programs (like rsyncd) expect to be able to 
  182.      * XXX re-initialize optind to 0 and have getopt_long(3) 
  183.      * XXX properly function again.  Work around this braindamage. 
  184.      */  
  185.     if (optind == 0)  
  186.         optind = 1;  
  187.   
  188. start:  
  189.     if (!*place) {                      /* update scanning pointer */  
  190.         if (optind >= nargc) {          /* end of argument vector */  
  191.             place = EMSG;  
  192.             if (nonopt_end != -1) {  
  193.                 /* do permutation, if we have to */  
  194.                 permute_args(nonopt_start, nonopt_end,  
  195.                     optind, nargv);  
  196.                 optind -= nonopt_end - nonopt_start;  
  197.             }  
  198.             else if (nonopt_start != -1) {  
  199.                 /* 
  200.                  * If we skipped non-options, set optind 
  201.                  * to the first of them. 
  202.                  */  
  203.                 optind = nonopt_start;  
  204.             }  
  205.             nonopt_start = nonopt_end = -1;  
  206.             return -1;  
  207.         }  
  208.         if ((*(place = nargv[optind]) != '-')  
  209.             || (place[1] == '/0')) {    /* found non-option */  
  210.             place = EMSG;  
  211.             if (IN_ORDER) {  
  212.                 /* 
  213.                  * GNU extension:  
  214.                  * return non-option as argument to option 1 
  215.                  */  
  216.                 optarg = nargv[optind++];  
  217.                 return INORDER;  
  218.             }  
  219.             if (!PERMUTE) {  
  220.                 /* 
  221.                  * if no permutation wanted, stop parsing 
  222.                  * at first non-option 
  223.                  */  
  224.                 return -1;  
  225.             }  
  226.             /* do permutation */  
  227.             if (nonopt_start == -1)  
  228.                 nonopt_start = optind;  
  229.             else if (nonopt_end != -1) {  
  230.                 permute_args(nonopt_start, nonopt_end,  
  231.                     optind, nargv);  
  232.                 nonopt_start = optind -  
  233.                     (nonopt_end - nonopt_start);  
  234.                 nonopt_end = -1;  
  235.             }  
  236.             optind++;  
  237.             /* process next argument */  
  238.             goto start;  
  239.         }  
  240.         if (nonopt_start != -1 && nonopt_end == -1)  
  241.             nonopt_end = optind;  
  242.         if (place[1] && *++place == '-') {  /* found "--" */  
  243.             place++;  
  244.             return -2;  
  245.         }  
  246.     }  
  247.     if ((optchar = (int)*place++) == (int)':' ||  
  248.         (oli = strchr(options + (IGNORE_FIRST ? 1 : 0), optchar)) == NULL) {  
  249.         /* option letter unknown or ':' */  
  250.         if (!*place)  
  251.             ++optind;  
  252.         if (PRINT_ERROR)  
  253.             fprintf(stderr, illoptchar, optchar);  
  254.         optopt = optchar;  
  255.         return BADCH;  
  256.     }  
  257.     if (optchar == 'W' && oli[1] == ';') {      /* -W long-option */  
  258.         /* XXX: what if no long options provided (called by getopt)? */  
  259.         if (*place)   
  260.             return -2;  
  261.   
  262.         if (++optind >= nargc) { /* no arg */  
  263.             place = EMSG;  
  264.             if (PRINT_ERROR)  
  265.                 fprintf(stderr, recargchar, optchar);  
  266.             optopt = optchar;  
  267.             return BADARG;  
  268.         } else              /* white space */  
  269.             place = nargv[optind];  
  270.         /* 
  271.          * Handle -W arg the same as --arg (which causes getopt to 
  272.          * stop parsing). 
  273.          */  
  274.         return -2;  
  275.     }  
  276.     if (*++oli != ':') {            /* doesn't take argument */  
  277.         if (!*place)  
  278.             ++optind;  
  279.     } else {                /* takes (optional) argument */  
  280.         optarg = NULL;  
  281.         if (*place)         /* no white space */  
  282.             optarg = place;  
  283.         /* XXX: disable test for :: if PC? (GNU doesn't) */  
  284.         else if (oli[1] != ':') {   /* arg not optional */  
  285.             if (++optind >= nargc) { /* no arg */  
  286.                 place = EMSG;  
  287.                 if (PRINT_ERROR)  
  288.                     fprintf(stderr, recargchar, optchar);  
  289.                 optopt = optchar;  
  290.                 return BADARG;  
  291.             } else  
  292.                 optarg = nargv[optind];  
  293.         }  
  294.         place = EMSG;  
  295.         ++optind;  
  296.     }  
  297.     /* dump back option letter */  
  298.     return optchar;  
  299. }  
  300.   
  301. /* 
  302.  * getopt_long -- 
  303.  *  Parse argc/argv argument vector. 
  304.  */  
  305. int  
  306. getopt_long(int nargc, char * const *nargv, const char *options,  
  307.         const struct option *long_options, int *idx)  
  308. {  
  309.     int retval;  
  310.   
  311.     assert(nargv != NULL);  
  312.     assert(options != NULL);  
  313.     assert(long_options != NULL);  
  314.     /* idx may be NULL */  
  315.   
  316.     if ((retval = getopt_internal(nargc, nargv, options)) == -2) {  
  317.         char *current_argv, *has_equal;  
  318.         size_t current_argv_len;  
  319.         int i, match;  
  320.   
  321.         current_argv = place;  
  322.         match = -1;  
  323.   
  324.         optind++;  
  325.         place = EMSG;  
  326.   
  327.         if (*current_argv == '/0') {        /* found "--" */  
  328.             /* 
  329.              * We found an option (--), so if we skipped 
  330.              * non-options, we have to permute. 
  331.              */  
  332.             if (nonopt_end != -1) {  
  333.                 permute_args(nonopt_start, nonopt_end,  
  334.                     optind, nargv);  
  335.                 optind -= nonopt_end - nonopt_start;  
  336.             }  
  337.             nonopt_start = nonopt_end = -1;  
  338.             return -1;  
  339.         }  
  340.         if ((has_equal = strchr(current_argv, '=')) != NULL) {  
  341.             /* argument found (--option=arg) */  
  342.             current_argv_len = has_equal - current_argv;  
  343.             has_equal++;  
  344.         } else  
  345.             current_argv_len = strlen(current_argv);  
  346.           
  347.         for (i = 0; long_options[i].name; i++) {  
  348.             /* find matching long option */  
  349.             if (strncmp(current_argv, long_options[i].name,  
  350.                 current_argv_len))  
  351.                 continue;  
  352.   
  353.             if (strlen(long_options[i].name) ==  
  354.                 (unsigned)current_argv_len) {  
  355.                 /* exact match */  
  356.                 match = i;  
  357.                 break;  
  358.             }  
  359.             if (match == -1)        /* partial match */  
  360.                 match = i;  
  361.             else {  
  362.                 /* ambiguous abbreviation */  
  363.                 if (PRINT_ERROR)  
  364.                     fprintf(stderr, ambig, (int)current_argv_len,  
  365.                          current_argv);  
  366.                 optopt = 0;  
  367.                 return BADCH;  
  368.             }  
  369.         }  
  370.         if (match != -1) {          /* option found */  
  371.                 if (long_options[match].has_arg == no_argument  
  372.                 && has_equal) {  
  373.                 if (PRINT_ERROR)  
  374.                     fprintf(stderr, noarg, (int)current_argv_len,  
  375.                          current_argv);  
  376.                 /* 
  377.                  * XXX: GNU sets optopt to val regardless of 
  378.                  * flag 
  379.                  */  
  380.                 if (long_options[match].flag == NULL)  
  381.                     optopt = long_options[match].val;  
  382.                 else  
  383.                     optopt = 0;  
  384.                 return BADARG;  
  385.             }  
  386.             if (long_options[match].has_arg == required_argument ||  
  387.                 long_options[match].has_arg == optional_argument) {  
  388.                 if (has_equal)  
  389.                     optarg = has_equal;  
  390.                 else if (long_options[match].has_arg ==  
  391.                     required_argument) {  
  392.                     /* 
  393.                      * optional argument doesn't use 
  394.                      * next nargv 
  395.                      */  
  396.                     optarg = nargv[optind++];  
  397.                 }  
  398.             }  
  399.             if ((long_options[match].has_arg == required_argument)  
  400.                 && (optarg == NULL)) {  
  401.                 /* 
  402.                  * Missing argument; leading ':' 
  403.                  * indicates no error should be generated 
  404.                  */  
  405.                 if (PRINT_ERROR)  
  406.                     fprintf(stderr, recargstring, current_argv);  
  407.                 /* 
  408.                  * XXX: GNU sets optopt to val regardless 
  409.                  * of flag 
  410.                  */  
  411.                 if (long_options[match].flag == NULL)  
  412.                     optopt = long_options[match].val;  
  413.                 else  
  414.                     optopt = 0;  
  415.                 --optind;  
  416.                 return BADARG;  
  417.             }  
  418.         } else {            /* unknown option */  
  419.             if (PRINT_ERROR)  
  420.                 fprintf(stderr, illoptstring, current_argv);  
  421.             optopt = 0;  
  422.             return BADCH;  
  423.         }  
  424.         if (long_options[match].flag) {  
  425.             *long_options[match].flag = long_options[match].val;  
  426.             retval = 0;  
  427.         } else   
  428.             retval = long_options[match].val;  
  429.         if (idx)  
  430.             *idx = match;  
  431.     }  
  432.     return retval;  
  433. }  
  434. #endif /* !GETOPT_LONG */  

 

拿过来后,把他们放到与destroy_linux.c同一目录下,只需要把destroy_linux.c的头文件改一个地方,#include <getopt.h>改为#include “getopt.h”,就能够编译运行了。而且,这样改好后,不仅在Tru64上能运行,在Linux、SunOS上也能运行。

[cpp]  view plain copy
  1. #include <stdio.h>  
  2. #include <stdlib.h>  
  3. #include <unistd.h>  
  4. #include "getopt.h"  
  5.   
  6. void print_usage(const char *program_name) {  
  7.     printf("%s 1.0.0 (2010-06-13)/n", program_name);  
  8.     printf("This is a program decoding a BER encoded CDR file/n");  
  9.     printf("Usage: %s -f <file_name> -o <output_name> [-c <config_name>] [-k <keyword>]/n", program_name);  
  10.     printf("    -f --file       the CDR file to be decoded/n");  
  11.     printf("    -o --output     the output file in plain text format/n");  
  12.     printf("    -c --config     the description file of the CDR file, if not given, use default configuration/n");  
  13.     printf("    -k --keyword    the keyword to search, if not given, all records will be written into output file/n");  
  14. }  
  15.   
  16. int main(int argc, char *argv[]) {  
  17.     char *file_name = NULL;  
  18.     char *output_name = NULL;  
  19.     char *config_name = NULL;  
  20.     char *keyword = NULL;  
  21.   
  22.     const char *short_opts = "hf:o:c:k:";  
  23.     const struct option long_opts[] = {  
  24.         {"help", no_argument, NULL, 'h'},  
  25.         {"file", required_argument, NULL, 'f'},  
  26.         {"output", required_argument, NULL, 'o'},  
  27.         {"config", required_argument, NULL, 'c'},  
  28.         {"keyword", required_argument, NULL, 'k'},  
  29.         {0, 0, 0, 0}  
  30.     };  
  31.     int hflag = 0;  
  32.   
  33.     int c;  
  34.     opterr = 0;  
  35.   
  36.     while ( (c = getopt_long(argc, argv, short_opts, long_opts, NULL)) != -1 ) {  
  37.         switch ( c ) {  
  38.             case 'h' :  
  39.                 hflag = 1;  
  40.                 break;  
  41.             case 'f' :  
  42.                 file_name = optarg;  
  43.                 break;  
  44.             case 'o' :  
  45.                 output_name = optarg;  
  46.                 break;  
  47.             case 'c' :  
  48.                 config_name = optarg;  
  49.                 break;  
  50.             case 'k' :  
  51.                 keyword = optarg;  
  52.                 break;  
  53.             case '?' :  
  54.                 if ( optopt == 'f' || optopt == 'o' || optopt == 'c' || optopt == 'k' )  
  55.                     printf("Error: option -%c requires an argument/n", optopt);  
  56.                 else if ( isprint(optopt) )  
  57.                     printf("Error: unknown option '-%c'/n", optopt);  
  58.                 else  
  59.                     printf("Error: unknown option character '//x%x'/n", optopt);  
  60.                 return 1;  
  61.             default :  
  62.                 abort();  
  63.         }  
  64.     }  
  65.   
  66.     if ( hflag || argc == 1 ) {  
  67.         print_usage(argv[0]);  
  68.         return 0;  
  69.     }  
  70.     if ( !file_name ) {  
  71.         printf("Error: file name must be specified/n");  
  72.         return 1;  
  73.     }  
  74.     if ( !output_name ) {  
  75.         printf("Error: output name must be specified/n");  
  76.         return 1;  
  77.     }  
  78.   
  79.     // if not setting default, Linux OK, but SunOS core dump  
  80.     if ( !config_name ) config_name = "(null)";  
  81.     if ( !keyword ) keyword = "(null)";  
  82.     printf("Parameters got: file_name = %s, output_name = %s, config_name = %s, keyword = %s/n", file_name, output_name, config_name, keyword);  
  83.     return 0;  
  84. }  

 

Linux下编译

-bash-3.2$ gcc -o destroy destroy.c getopt_long.c

短格式,全部输入

-bash-3.2$ ./destroy -f aaa -o aaa.txt -c ccc -k 222

Parameters got: file_name = aaa, output_name = aaa.txt, config_name = ccc, keyword = 222

前两个长格式,后两个短格式

-bash-3.2$ ./destroy --file aaa --output aaa.txt -c ccc -k 222

Parameters got: file_name = aaa, output_name = aaa.txt, config_name = ccc, keyword = 222

漏掉一个必须输入的参数会报错

-bash-3.2$ ./destroy -output aaa.txt

Error: file name must be specified

次序随意,长短混用

-bash-3.2$ ./destroy -c ccc -o aaa.txt -k 222 --file aaa

Parameters got: file_name = aaa, output_name = aaa.txt, config_name = ccc, keyword = 222

 

题外话,#include <filename.h>与#include “filename.h”有什么区别,是面试C程序员经常问到的一个问题。答案大家都知道了,#include <filename.h>,编译器从标准库路径搜索filename.h,而#include “filename.h”,编译器从用户的工作路径搜索filename.h。

 

此外,网上也有人说从glibc(http://sourceware.org/glibc/)上把getopt.h、getopt.c和getoptl.c拿过来也能够用。我也试过,但是不清楚什么原因不成功。

 

在这个小实验的过程中,还发现了C语言在各个OS下的一些细小差异,比如destroy.c里,79行到82行:

// if not setting default, Linux OK, but SunOS core dump

if ( !config_name ) config_name = "(null)";

if ( !keyword ) keyword = "(null)";

printf("Parameters got: file_name = %s, output_name = %s, config_name = %s, keyword = %s/n", file_name, output_name, config_name, keyword);

 

如果在81行和82行不设置空指针的默认值,Linux和Tru64都会自动帮你转换而避免运行时错误,但是SunOS不会,它会死给你看。

./destroy -f aaa -o aaa.txt

Segmentation Fault (core dumped)

 

再比如第62行的abort()在头文件stdlib.h中定义,如果不包含此文件,SunOS与Tru64编译都没问题,Linux编译时会警告:

warning: incompatible implicit declaration of built-in function abort

 

由此看来,虽然C也公认是可移植性比较好的语言,但是在跨平台的项目中,也应该注意这些微小的差别。




转自:http://blog.csdn.net/lanmanck/article/details/11999345

windows 命令行参数解析编程,getopt的windows版本 windows 命令行参数解析编程 Linux系统下处理命令行参数的编程比较简单,使用getopt即可快速的处理。 windowds系统下,没有getopt函数处理命令行参数,但是可以对getopt的源码进行简单的修改即可在windows程序进行命令行参数处理。 示例如下: // getopt.h /* Declarations for getopt. Copyright (C)... 阅读详情

相关推荐

C语言命令行参数解析:从argc/argv基础到getopt_long实战

命令行参数是程序与操作系统交互的基础接口,它允许用户在执行程序时动态传递配置和数据。其核心原理是通过main函数的argc和argv参数接收并解析用户输入,argc记录参数数量,argv存储参数字符串数组。这一机制的技术价值在于实现了程序的灵活性和可配置性,是构建命令行工具、脚本和系统服务的基石。在实际应用场景中,从简单的文件操作到复杂的编译工具链,都依赖命令行参数进行功能定制。本文聚焦于C语言中的参数处理,详细解析argc与argv的内存布局与访问方式,并深入探讨如何使用getopt和getopt_lon

weixin_30216561的博客 405

linux程序 option,long-option.c/解析命令行参数

#include //继续ing。。。#include "version-etc.h"//初始化结构体static struct option const long_options[] ={{"help", no_argument, NULL, 'h'},{"version", no_argument, NULL, 'v'},{NULL, 0, NULL, 0}};这里贴一下从网上找到的中文解释(...

weixin_36164428的博客 1192

C/C++命令行参数解析:getopt函数族原理与实战指南

命令行参数解析是程序与用户交互的基础技术,其核心在于将用户输入的字符串序列转化为程序内部可处理的结构化数据。传统手动解析argv数组的方式不仅代码冗余,且难以处理短选项、长选项、带参选项等复杂组合,易引入错误。getopt函数族作为POSIX标准的一部分,通过定义选项字符串和结构体数组,实现了参数解析的标准化与自动化,显著提升代码健壮性和可维护性。在C/C++开发中,尤其在构建需要复杂配置的命令行工具(如涉及ncurses库的项目)时,掌握getopt及其增强版getopt_long至关重要。本文以工程实践

weixin_34259232的博客 514

Linux下getopt_long函数的使用

getopt_long为解析命令行参数函数,它是Linux C库函数。使用此函数需要包含系统头文件getopt.h。 getopt_long函数声明如下: int getopt_long(int argc, char * const argv[], const char *optstring, const struct option *longopts, int *longindex); ...

网络资源是无限的 1万+

uniapp+萤石视频监控实战:解决ezuikit.js真机调试不显示的5个关键步骤

本文针对Uniapp集成萤石视频监控时ezuikit.js在真机调试中黑屏不显示的问题,提供了5个关键解决步骤。核心方案是采用Webview加载独立H5播放页,以规避跨平台环境差异,并详细阐述了资源放置、多端适配、通信处理及系统化排查方法,确保视频流稳定播放。

weixin_29001655的博客 296

SAP HR模块配置假期日历和缺勤类型

SAP的HR模块。业务顾问在实施时一般会配置未来10年的假期日历,到期后再进行配置。同时,增加请假类型(缺勤信息类型)。记录这一过程。

福来阁86号技师的妖孽日常 5539

struct option 的使用

#include <stdio.h> #include <getopt.h> char *l_opt_arg; char* const short_options = "nl:b"; //我设置l是要接参数的。所以l后面有个冒号 //l: means after l there should hava an argument struct option long_options[] = {

show me code 2567

ENVI新手避坑指南:手把手教你搞定遥感影像的坐标系转换(附ArcGIS对比)

本文详细解析ENVI与ArcGIS在遥感影像坐标系转换中的关键差异与实战技巧,特别针对新手常见问题提供避坑指南。从基础概念到高级操作,涵盖定义投影、UTM转换等核心步骤,并对比两种软件的处理精度与效率,帮助用户高效完成遥感影像处理任务。

weixin_42531925的博客 384

linux getopt long,Linux命令行参数解析——getopt_long

在linux中,一切皆文件,所有的可执行程序都可以通过命令行启动,程序启动时通常都会带上各种参数以控制程序的行为。所以解析命令行参数通常是一个可执行程序的第一步,下面就来介绍下经常用到的命令行参数的解析函数——getopt_long。我们先来了解一下命令行参数。命令行参数可以分为两类,一类是短选项,一类是长选项。在命令行中"-"表示短选项,"--"则表示长选项。例如,在linux中最常用的ls命令...

weixin_32869031的博客 509

YOLO26源码深度解析:从主干网络到端到端部署优化

目标检测模型在工业落地中,不仅需要精度,更要求训练稳定、推理高效。YOLO系列近年持续演进,出现了代号为YOLO26的实验性整合版本,其核心思路是融合重参数化卷积、SPD模块、可学习跨尺度融合与双分支一致性分配等机制,兼顾小目标检测与端到端推理。从源码角度看,模型配置文件定义了分层结构,前向数据流保留了主干-颈部-输出头的经典范式,但在细节上通过空间重排列降低下采样信息丢失,并针对训练与推理设计了可折叠的算子结构。这种设计使得导出时无需复杂后处理,配合算子融合与真实数据量化,可在边缘设备上获得稳定的检测性能

weixin_28224217的博客 253

图解联合概率密度、边缘概率密度、条件概率密度之间的关系

简要图解联合概率密度、边缘概率密度、条件概率密度之间的关系

一个搬运知识的笨小孩 2万+

C语言中命令行参数处理

C语言中命令行参数处理-getopt_long函数

大草的博客 2378

python批量调用大模型API:多线程和异步协程

本文介绍了利用多线程技术批量调用大模型API的实现方法。核心是通过并发请求提高处理效率,主要采用线程池管理并发数量、结果聚合等技术。文章提供了一个完整的Python实现示例,包含APIBatchCaller类及其single_api_call和batch_call方法,详细解析了并发控制、错误处理等关键点,并给出了使用注意事项,包括并发数设置、重试策略和超时处理等。该方案特别适合IO密集型任务,能显著提升批量API调用的效率。

Cachel Wood的博客 763

使用getopt_long()从命令行获取参数,struct option

本文来自:http://blog.csdn.net/yui/article/details/5669922 众所周知,C程序的主函数有两个参数,其中,第一个参数是整型,可以获得包括程序名字的参数个数,第二个参数是字符数组指针或字符指针的指针,可以按顺序获得命令行上各个字符串参数。其原形是: int main(int argc, char *argv[]); 或者 int

501

API深度集成——OpenClaw与第三方服务无缝对接(2026实战版)

本文介绍了OpenClaw系统与第三方服务的API深度集成技术,重点阐述了RESTful API的实现方案。通过一个功能完善的REST客户端类(RestClient)展示了核心功能:支持请求重试、拦截器机制、错误处理和认证管理等;同时提供了API资源管理器(ApiResourceManager)简化资源操作。这些技术实现了OpenClaw与外部系统的稳定可靠对接,为开发者构建API集成方案提供了2026年的最佳实践。

博客 1220

InTheHand.Net.Personal+BlueTooth4,蓝牙开发

项目中有蓝牙开发的必备dll,现在网上相关的文档博客不少,有的说的多有的说少,但是却很少有这两个dll,分享一下。

linux c 解析命令行参数 getopt_long(); / struct option

一、命令行参数 命令行参数可以分为两类,一类是短选项,一类是长选项,短选项在参数前加一杠"-",长选项在参数前连续加两杠"–",如下表(ls 命令参数)所示,其中-a,-A,-b都表示短选项,–all,–almost-all, --author都表示长选项。他们两者后面都可选择性添加额外参数。比如–block-size=SIZE,SIZE便是额外的参数。 短参数与后面的值可以加空格,也可以不加空格。如-a 1 和 -a1是相同的。 长参数与后面的值可以加空格,也可以用=号连接。如–byte 3 和–byte

Hakuura天下第一可爱 810

贝叶斯统计 [韦来生编]

贝叶斯(Bayes)统计是近几十年来迅速发展起来的数理统计的一个重要分支。贝叶斯方法与经典统计方法的主要不同之处是进行统计推断时除了利用样本信息外,还要利用参数的先验信息,因此可以提高统计推断或统计决策的效果。它在经济、金融、生物、医学、自然科学和社会科学等许多领域具有广泛的应用。贝叶斯方法的研究已渗透到了统计学的几乎所有领域。作者在给中国科学技术大学概率论与数理统计专业本科生开设的“数理统计”课程中有一章专门讲授“贝叶斯方法和统计决策理论”,近十年来也给中国科学技术大学概率统计专业研究生开设过几次“贝叶斯分析”课。本书是在对过去讲稿的内容作了适当的增减和调整的基础上完成的。  本书共分六章。第1章是绪论,介绍了贝叶斯统计的若干基本概念,同时对必要的数理统计的基础知识有重点地作了回顾。第二章介绍了确定先验分布的若干可供选择的方法。第三章介绍了几类常见统计模型参数的后验分布的主要结果和计算方法。第四章和第五章分别介绍了“贝叶斯统计推断”和“贝叶斯统计决策”的内容。第六章介绍了贝叶斯统计计算的若干方法,包括蒙特卡洛方法和马尔可夫链蒙特卡洛(MCMC)方法以及相关统计软件的简介。本书的每一章附右大量的例题和习题,书末附有常用的几个表格和部分习题解答供读者查用。  大约可在54学时内讲授本书的第1章至第六章的主要内容,教师可根据学时需要选讲本书第1章至第六章的部分内容。书中标“*”号的章节可略去不讲,留给读者作为阅读材料。第六章例题中的R代码和部分例题的数据文件等可从作者个人主页下载。  作者在编写本书的过程中参考了J.O.Berger教授的《统计决策论及贝叶斯分析》和茆诗松教授编写的《贝叶斯统计》等书中的一些内容,以及《贝叶斯分析》一书中由张伟平博士编写的有关贝叶斯统计计算的一些内容。在此表示衷心感谢。  本书编写准备过程中,中国科学技术大学统计与金融系的几个研究生帮助完成了本书部分中文的录入和排版,作者对他们的辛勤工作表示真诚的感谢。高等教育出版社为本书的出版给予了大力支持。在此一并致谢。

linux命令行参数解析(getopt和getopt_long)

使用函数getopt_long /*在文件getopt_ext.h中有以下声明*/ struct option { const char *name; /* has_arg can't be an enum because some compilers complain about type mismatches in all the code that assumes it is an int. */ int has_arg; int *flag; int val; };

yyh23的博客 439

Data-Structures-and-Algorithm-Analysis-in-Java.pdf

作者: Weiss, Mark A. 出版社: Addison Wesley Data Structures and Algorithm Analysis in Java is an “advanced algorithms” book that fits between traditional CS2 and Algorithms Analysis courses. In the old ACM Curriculum Guidelines, this course was known as CS7. This text is for readers who want to learn good programming and algorithm analysis skills simultaneously so that they can develop such programs with the maximum amo...

基于Linux下的getopt()/getopt_long()函数进行参数解析

getopt/getopt_long函数进行参数解析1.参数原型2.参数和返回值分析 1.参数原型 getopt()函数的参数原型 int getopt(int argc, char * const argv[], const char *optstring); getopt_long()函数的参数原型 int getopt_long(int argc, char * const argv[], ...

AJIEIT的博客 344

linux getopt_long函数,linux解析命令行选项getopt_long用法解读

linux解析命令行选项getopt_long用法在程序中难免需要使用命令行选项,可以选择自己解析命令行选项,但是有现成的,何必再造轮子。下面介绍使用getopt_long解析命令行选项。程序中主要使用:短选项 长选项 是否需要参数 备注-v --version 否 查询版本号-n --name 是(用户名) 指定使用者-d --debug 否 是否已测试1、函数出处复制代码代码如下:[cp...

weixin_42128015的博客 264

linux 输入参数利用getopt、struct option、getopt_long、getopt_long_only解析

参考:点击查看详细解释 1、struct option 结构体 struct option { const char *name; int has_arg; int *flag; int val; }; 含义如下: name指明长选项的名称; has_arg指明该选项是否带参数,1为是,0为否,2为可选; flag指明长选项如何返回,如果flag为NULL,则get

sinat_29830917的博客 1724

getopt_long使用详解及实例

getopt_long 是一个在 Linux 和类 Unix 系统中常用的函数,用于解析命令行参数。它支持短选项(如 -a)和长选项(如 --long-option),并且能够处理带有参数的选项。以下是 getopt_long 的详细使用方法返回值如果遇到有效的短选项或长选项,getopt_long 返回该选项的字符(对于短选项)或 val(对于长选项)。如果所有选项都已处理完毕,返回 -1。如何得带参选项的参数值。

欲盖弥彰1314 953

linux c "struct option"解析命令参数

在c程序应用程序执行的时,常常配有一些参数,如果参数少我们可以使用arvg,arvc来实现,如果参数很多并且需要传入参数复杂我们可以使用strcut option 来实现。 1. struct option介绍 struct option { const char *name; //name表示的是长参数名 int has_arg; //has_arg有3个值,no_argument(或者...

weixin_40751385的博客 1893

linux 参数解析,Linux 命令行参数解析

在linux中,经常需要各种命令,通常情况下都会带各种参数,而这些参数是如何解析的呢?通常使用GNU C提供的函数getopt、getopt_long、getopt_long_only函数来解析命令行参数。使用他们需要引用头文件getopt.h。1. getopt()函数getopt()用来解析命令行选项参数的,但是只能解析短选项: -d 100,不能解析长选项:--prefix;其原型:int ...

weixin_36257615的博客 774
上一篇: 深入理解CMA
下一篇: Linux 信号详解一(signal函数)
gnnulzy
博客等级 码龄12年 56粉丝 5原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值