getopt函数用法

getopt函数原型:

#include <fcntl.h>
int getopt(int argc,const* const argv[],const char *option);
extern int optind,opterr,optopt;
extern char *optarg;
                                                                 返回值:下一个选项字符,若全部选项处理完毕则返回-1

描述:getopt函数是用来解析命令行参数的, 以‘-’或‘--’开头的参数为选项元素,除去‘-’或‘--’的选项元素

为选项字符。如果getopt函数被重复调用,则它将会依次返回每个选项元素中的选项字符。

getopt的通常用法是一个循环,当getopt返回-1时结束循环。在每次循环中,getopt会返回下一个处理的选项。由应用程序来处理选项中的冲突,实际上,getopt仅仅简单地分析命令选项并强制执行选型的标准格式而已。

当遇到一个不合法的选项时,getopt返回一个问号而不是一个字符。如果选项的参数缺失,getopt也会返回一个问号,但是如果选项字符串中第一个字符是冒号,getopt会返回一个冒号。特殊模式--会让getopt停止处理并返回-1。这可以让用户提供一个以负号开头的命令参数而非选型。例如,如果有一个文件名为-bar,则不可以通过输入下列命令来删除之。

rm -bar

因为rm会尝试将-bar解释成选项。可以用下列方式来删除文件:

rm -- -bar

有几个全局变量与getopt函数解析参数有关:

optind: int型, 指示下一个要解析的参数位置,初始时为1 下一个要处理的字符串的argv数组的下标。该下标从1开始,每个参数被getopt处理后增量。

optarg: char *, 必须接参数的选项元素的参数, 如上面的-nxzz, optarg 就指向"xzz"字符串,如果选项带参数,处理该选项时,getopt将optarg指向该选项的参数字符串

opterr: int 型, 设为0将不打印错误信息.如果遇到一个选项错误,getopt默认动作是会打印一个错误信息。为了禁止该行为,应用程序可以将opterr设为0

optopt:如果在处理选项过程中遇到错误,getopt将optopt指向引起错误的选项字符串。

函数原型为:  int getopt(int argc, char * const argv[], const char *optstring);


参数说明: 前两个参数与main函数参数相同, argc保存参数个数,argv[]保存参数数组,第三个参数optstring是你定义

的选项字符组成的字符串, 如"abc",表示该命令有三个选项元素 -a, -b, -c, 选项字符后面如果有一个冒号说

明该选项元素一定有一个参数, 且该参数保存在optarg中如"n:t", 表示选项元素n后要接参数, 选项元素t后

不接参数,如 -n xzz -t 或 -nxzz t,有两个冒号说明该选项可接可选参数, 但可选参数不保存在optarg中.


返回值: 如果当前处理的参数为选项元素,且该选项字符在optstring字符串中, 即为你定义的选项, 则返回该

选项字符,如果该选项字符不是你定义的, 那么返回字符'?', 并更新全局变量optind, 指向argc数组中的下一

个参数. 如果当前处理的参数不是选项元素, 则optind偏移向下一个参数, 直到找到第一个选项元素为止,  然后

再按之前描述的操作,如果找不到选项元素, 说明解析结束, 则返回-1.

下面看例子: 

[plain]  view plain copy
  1. #include <unistd.h>                                                                                                         
  2. #include <getopt.h>  
  3.   
  4. int main(int argc, char * const argv[])  
  5. {  
  6.         int opt;  
  7.         while ((opt = getopt(argc, argv, "nb:o::t")) != -1) {  
  8.                 printf("opt = %c, optarg = %s, optind = %d, argv[%d] = %s\n",   
  9.                                 opt, optarg, optind, optind, argv[optind]);  
  10.         }  
  11.         return 0;  
  12. }  

假设编译好的可执行文件名为test, test有3个有效参数-n, -b, -t, 其中-n, -t后不接参数, -b后一定要接参数, -o后接可选参数.

# ./test -x -y -z                <------ 无效参数, 会打印错误信息, 并返回字符'?'

输出:

[plain]  view plain copy
  1. ./getopt: invalid option -- 'x'  
  2. opt = ?, optarg = (null), optind = 2, argv[2] = -y  
  3. ./getopt: invalid option -- 'y'  
  4. opt = ?, optarg = (null), optind = 3, argv[3] = -z  
  5. ./getopt: invalid option -- 'z'  
  6. opt = ?, optarg = (null), optind = 4, argv[4] = (null)  


# ./test -n -b xzz -t

[plain]  view plain copy
  1. opt = n, optarg = (null), optind = 2, argv[2] = -b  
  2. opt = b, optarg = xzz, optind = 4, argv[4] = -t                <----------- optarg 指向选项元素的参数, 并且optind跳过了该参数, 直接指向了-t参数  
  3. opt = t, optarg = (null), optind = 5, argv[5] = (null)  


# ./test -n -bxzz -t                            <------------- 也可将选项参数与其接的参数写在一起

[plain]  view plain copy
  1. opt = n, optarg = (null), optind = 2, argv[2] = -bxzz  
  2. opt = b, optarg = xzz, optind = 3, argv[3] = -t                <----------- optind 同样将指向下一个参数-t  
  3. opt = t, optarg = (null), optind = 4, argv[4] = (null)  


# ./test -b -t

[plain]  view plain copy
  1. opt = b, optarg = -t, optind = 3, argv[3] = (null)      <----------- 将-t当成了选项元素-b的参数, 之后就不再解析-t, optind为3  

# ./test -t -b         <---- -b缺少参数

[plain]  view plain copy
  1. opt = t, optarg = (null), optind = 2, argv[2] = -b  
  2. ./getopt: option requires an argument -- 'b'  
  3. opt = ?, optarg = (null), optind = 3, argv[3] = (null)  

# ./test -t a -b xzz           <------- 命令行中有一个无用参数 a, 解析时被忽略了, 因为-t不需要接参数

[plain]  view plain copy
  1. opt = t, optarg = (null), optind = 2, argv[2] = a  
  2. opt = b, optarg = xzz, optind = 5, argv[5] = (null)  

# ./test -ntb xzz               <--------- 还可以把参数连在一起写

[plain]  view plain copy
  1. opt = n, optarg = (null), optind = 1, argv[1] = -ntb  
  2. opt = t, optarg = (null), optind = 1, argv[1] = -ntb  
  3. opt = b, optarg = xzz, optind = 3, argv[3] = (null)  

# ./test -t -o -b xzz    <----- -o选项不接参数

[plain]  view plain copy
  1. opt = t, optarg = (null), optind = 2, argv[2] = -o  
  2. opt = o, optarg = (null), optind = 3, argv[3] = -b  
  3. opt = b, optarg = xzz, optind = 5, argv[5] = (null)  

# ./test -t -o 10 -b xzz   <------ -o选项接参数10

[plain]  view plain copy
  1. opt = t, optarg = (null), optind = 2, argv[2] = -o  
  2. opt = o, optarg = (null), optind = 3, argv[3] = 10          <------------------ <strong><span style="color:#ff0000;">可以看到10并没有保存在optarg中</span></strong>  
  3. opt = b, optarg = xzz, optind = 6, argv[6] = (null)        <-----------------  而-b的参数则保存在optarg中了  


常用用法: 

一般是用while循环配合switch语句来使用getopt函数解析参数, 如下:

[plain]  view plain copy
  1. /*  
  2.  *  得到参数信息  
  3.  */  
  4. int getinfo(int argc,  char * const argv[], int *ps, int *pE, int *pb, char *trace_name, int *vflag)  
  5. {  
  6.         int opt;  
  7.         int count_arg = 0;  
  8.         opterr = 0;  
  9.         while ((opt = getopt(argc, argv, "vs:E:b:t:")) != -1) {  
  10.                 switch (opt) {  
  11.                 case 'v':  
  12.                         *vflag = 1;       
  13.                         break;  
  14.                 case 's':  
  15.                         ++count_arg;  
  16.                         *ps = atoi(optarg);       
  17.                         break;  
  18.                 case 'E':  
  19.                         ++count_arg;  
  20.                         *pE = atoi(optarg);  
  21.                         break;  
  22.                 case 'b':  
  23.                         ++count_arg;  
  24.                         *pb = atoi(optarg);  
  25.                         break;  
  26.                 case 't':  
  27.                         ++count_arg;  
  28.                         strcpy(trace_name, optarg);  
  29.                         break;  
  30.                 default:        /* '?' */  
  31.                         Usage();  
  32.                         exit(-1);  
  33.                         break;  
  34.                 }  
  35.         }  
  36.           
  37.         if (count_arg < 4) {  
  38.                 Usage();  
  39.                 exit(-1);  
  40.         }  
  41.         return 0;  
  42. }  
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C语言的getopt()函数用于分析命令行参数。它的声明为: int getopt(int argc, char * const argv[], const char * optstring); 该函数通过解析命令行参数来获取选项和参数的值。用户可以在命令行中使用不同的选项来传递参数给程序。 下面是一个getopt()函数的示例代码: #include <unistd.h> #include <stdio.h> int main(int argc, char * argv[]){ int i; printf("%s\n","argv原序:"); for(i = 0;i < argc;i++){ printf("%s ",argv[i]); } printf("\n"); printf("START@optind:%d,opterr:%d\n",optind,opterr); int ret; while((ret = getopt(argc,argv,"aW;b:c:de::")) != -1){ switch(ret){ case 'a': printf("Having option -a\n"); break; case 'b': printf("having option -b,and its argument is %s\n",optarg); break; case 'c': printf("having option -c,and its argument is %s\n",optarg); break; case 'd': printf("Having option -d\n"); break; case 'e': printf("having option -e,it is optional,and its argument is %s\n",optarg); break; case '?': printf("Unknown option -%c\n",(char)optopt); break; } } printf("END@optind:%d,argv[%d]:%s\n",optind,optind,argv[optind]); printf("%s\n","argv现序:"); for(i = 0;i < argc;i++){ printf("%s ",argv[i]); } printf("\n"); return 0; } 该示例演示了如何使用getopt()函数解析命令行参数。程序通过指定选项和参数的形式来接受用户输入,并根据不同的选项执行不同的操作。在示例中,选项包括:a、b、c、d和e,其中e选项是可选的。通过在命令行中输入相应的选项和参数,程序会根据不同的选项执行相应的代码逻辑。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [C语言中getopt()函数和select()函数的使用方法](https://download.csdn.net/download/weixin_38621104/14868224)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *2* *3* [C语言——getopt函数](https://blog.csdn.net/weixin_40763897/article/details/87898328)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值