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

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

本文来自:http://blog.csdn.net/yui/article/details/5669922

众所周知,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也公认是可移植性比较好的语言,但是在跨平台的项目中,也应该注意这些微小的差别。

getopt()与getopt_long()的使用简介 感性认识 getopt()与getopt_long()是专门处理命令行参数的两个函数,getopt()处理短参数,getopt_long()处理长参数。还不明白请看下面这张图: 解析 -t yiqi 就是这两个函数做的事,下面我们一起来看看究竟如何使用好这两个函数。还不明白的请看下图: 非常清楚,命令行参数由Command name,Option,Option argument以及Operands组成。 Command name不用多说,就是程序的名称。 操作对象Operands又称no. 阅读详情

相关推荐

windows 命令行参数解析编程,getopt的windows版本

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

linux 1592

C语言linux getopt_long()函数(命令行解析)(getopt、getopt_long_only)(短选项 -,长选项 --)(option结构体)(optind、optarg变量)

参考文章:浅谈linux的命令行解析参数之getopt_long函数 文章目录前言一、关于命令行参数二、getopt_long函数参数以及返回值介绍(以上三个函数都适用):1、argc和argv和main函数的两个参数一致。2、optstring: 表示短选项字符串。3、longopts:表示长选项结构体。结构如下:4、longindex:longindex非空,它指向的变量将记录当前找到参数符合longopts里的第几个元素的描述,即是longopts的下标值。5、全局变量:6、返回值:三、测试(自行测试

Dontla的博客 1万+

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

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

weixin_30216561的博客 405

浅谈linux的命令行解析参数之getopt_long函数

前言         在linux中,经常需要各种命令,通常情况下都会带各种参数,而这些参数是如何解析的呢?通常使用GNU C提供的函数getopt、getopt_long、getopt_long_only函数来解析命令行参数。一、关于命令行参数     命令行参数可以分为两类,一类是短选项,一类是长选项,短选项在参数前加一杠"-",长选项在参数前连续加两杠"--",如下表(ls 命令参数)所示,...

爱拼才会赢 7万+

linux 下grep命令C代码实现

#if HAVE_NBTOOL_CONFIG_H #include "nbtool_config.h" #endif #include __RCSID("$NetBSD: grep.c,v 1.11 2012/05/06 22:27:00 joerg Exp $"); #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "grep.h" #ifndef WITHOUT_NLS #include nl_catd catalog; #endif /* * Default messags to use when NLS is disabled or no catalogue * is found. */ const char *errstr[] = { "", /* 1*/ "(standard input)", /* 2*/ "cannot read bzip2 compressed file", /* 3*/ "unknown %s option", /* 4*/ "usage: %s [-abcDEFGHhIiJLlmnOoPqRSsUVvwxZz] [-A num] [-B num] [-C[num]]\n", /* 5*/ "\t[-e pattern] [-f file] [--binary-files=value] [--color=when]\n", /* 6*/ "\t[--context[=num]] [--directories=action] [--label] [--line-buffered]\n", /* 7*/ "\t[pattern] [file ...]\n", /* 8*/ "Binary file %s matches\n", /* 9*/ "%s (BSD grep) %s\n", };

杰理芯片外挂Flash音乐播放功能避坑指南(附FAT文件系统配置)

本文详细解析了杰理芯片外挂Flash实现音乐播放功能的技术要点与常见问题,包括硬件连接、SPI驱动配置、FAT文件系统烧录及音乐播放集成等关键环节。特别针对Flash选型、FAT文件系统配置等易错点提供实用解决方案,帮助开发者高效完成嵌入式音频系统开发。

yhn45678901的博客 842

getopt 和 getopt_long 命令行解析函数

getopt 和 getopt_long 命令行解析函数

hinewcc的博客 4009

【斯坦福计网CS144项目】环境配置 & Lab0: ByteStream

前言 感觉学了不少 C++ 编程的知识和技术但比较缺少实践,于是打算找一些项目跟着做一做。 首先安利一个自学网站 CS自学指南,北大的同学做的,汇总了很多国内外高校 CS 相关的高质量公开课,其中大部分是有课程项目的。翻了翻感觉 Stanford 的这门 CS144 计网课的 Lab 比较有趣,难度也不错,就是它了! 课程网址:CS 144: Introduction to Computer Networking 我跟的是 2021 Fall 学期的版本。 准备工作 在上面的网站中先把 8 个实验的文档(

アルタイル 8168

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

函数说明#include函数说明:函数getopt用来解析命令行参数。函数getopt_long支持长选项的命令行解析。函数原型:intgetopt_long(int argc, char* constargv[],                      const char*optstring,                     const struct option*longopts...

gnnulzy的博客 640

eda、gnm、anm究竟是个啥?

eda:主成分分析 gnm:高斯网络模型 anm:各向异性网络模型

药研猿的博客 1252

广义标签多伯努利滤波器(GLMB):多目标跟踪中的动态身份维护理论与算法解析

目标集表示Xx1l1x2l2xNlNX{(x1​l1​x2​l2​xN​lN​)}xi∈Rdxi​∈Rd为目标状态(如位置、速度),li∈Lli​∈L为唯一标签(可数无限集,如自然数序列),N 为目标数(允许N0N=0N0,即空集)。GLMB 通过广义化标签多伯努利分布,将多目标跟踪从 “状态估计” 提升至 “动态身份 - 状态联合建模”,成为复杂场景下精准跟踪的核心技术。

qq_44965657的博客 1617

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

标题:Stata17安装后遇到Java安装问题解决方法

设置JAVA_HOME环境变量:在Windows上,您需要设置JAVA_HOME环境变量以告诉Stata Java的安装路径。d. 输入变量名为JAVA_HOME,变量值为Java安装路径。注意:请确保您的Java版本与Stata兼容,并使用正确的Java安装路径。设置Stata的Java安装路径:现在,您需要告诉Stata Java的安装路径。如果您看到Java版本信息,则表示Java已成功安装。如果没有安装,请先下载并安装Java。确认Java已安装:首先,请确保您的计算机上已经正确安装了Java。

CyberSparkZ的博客 2876

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

uniapp H5刷新页面后返回按钮失效问题完美解决方案

这个问题其实很隐蔽,尤其是uniapp H5 场景下刷新导致栈清理,很多开发者一开始都懵掉了。uniapp 内部对「页面栈只有一个」时的返回逻辑是reLaunch;所以只要在这个分支里替换为自己的逻辑(比如),就能顺利实现预期。目前我在项目里已经跑通了,暂时没发现问题。不得不说,知道源码里这个逻辑后,真的是醍醐灌顶,只能膜拜框架大佬了 🤯。

代码简单说 Vue、JAVA、PHP、Node.js 熟练运用,接口、架构、性能全搞定。 532

ChatTutor:让AI老师“会写会画”,打造可视化、互动式智能教育新范式

ChatTutor是一款突破性的开源AI教学助手,通过可视化电子白板实现"边讲边写"的沉浸式教学体验。该项目支持数学公式手写输入、动态函数绘图、自动生成思维导图等功能,采用多智能体架构实现专业协同。未来将扩展至编程、物理等STEM教育领域,适用于学生自学、教师备课和教育平台集成。作为MIT协议开源项目,ChatTutor通过赋予AI"教学肢体语言",推动教育从信息传递转向可视化互动建构,重新定义了AI助教的可能性。

这里汇聚了前沿的技术分享与实用的开发技巧,带你探索从创意到企业的技术创业之路。 444

c语言命令行参数解析函数 getopt_long() 使用

本文介绍了C语言中解析命令行参数的getopt_long()函数使用方法。通过示例代码展示了如何定义短选项(如"hi:")和长选项结构体数组(如{"help",no_argument,NULL,'h'})。函数支持三种参数类型:无参数、必需参数和可选参数。文章详细说明了函数原型、选项字符串规则、长选项数组定义、返回值含义以及相关全局变量(optarg、optind)。测试案例验证了-h/--help、-i/--input等选项的解析效果,并指出未定义的-o选项会导致错

hjjdebug的专栏 924

rk3399开发环境的介绍

由于Bluez的介绍文档有限,以及对Linux 系统/驱动概念、D-Bus 通信和蓝牙协议都有要求,加上网络上其实没有一个完整的介绍Bluez系列的文档,所以不管是蓝牙初学者还是蓝牙从业人员,都有不小的难度,学习曲线也相对较陡,所以我有了这个想法,专门对Bluez做一个系统性的介绍,尽可能的涵盖所有内容。

朝气蓬勃 715

getopt_long 函数解析命令行参数时的 struct option

staticconststructoptionoptions[]={ {"help",no_argument,NULL,'h'}, {"output",required_argument,NULL,'o'}, {"level",required_argument,NULL,'l'}, {"size",required_argument,NULL,'s'}, {"symversion",...

like_study_cat的博客 378

Camera2Demo

在Camera2 的基础上进行封装,使得Camera2一堆初始化逻辑与Activity分离,降低耦合度,完成预览拍照并保存的操作

霍尼韦尔SoftMaster使用说明

霍尼韦尔SoftMaster使用说明

深入理解 getopt_long,getopt_long_only

getopt_long, getopt_long_only – 命令行解析函数,支持长选项解析 【说明】 getopt_long/getopt_long_only 是 getopt 的泛集,getopt 是 getopt_long 的一个子集,getopt 支持的所有特性,getopt_long 都支持,包括错误打印、argv 元素顺序调整等;getopt_long 相比 getopt 增加了长选...

amei113的专栏 1811

jre9下载 jdk9

(Java SE Runtime Environment 9.0) 9.0u175 官方最新版 【x86|x64】

struct option结构定义

转自:http://blog.sina.com.cn/s/blog_4db5519f01014j77.html 在该函数中,初始化结构体数组:const struct option longOptions[],其原型定义在getopt.h中: #defineno_argument       0 #define required_argument  1 #define optional

happy803的专栏 8017

复分析 阿尔福斯(Ahlfors) 第三版答案 英文

答案分为十章,有部分习题没有答案,全英文复分析阿尔福斯(Ahlfors) 第三版答案

基于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
上一篇: 【图形学】我理解的伽马校正(Gamma Correction)
下一篇: dma_alloc_coherent和dma_alloc_writecombine的区分
Louis___Xu
博客等级 码龄18年 5粉丝 8原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值