解析带有多个参数的命令行选项[getopt?]

编程入门 行业动态 更新时间:2024-10-24 04:44:31
本文介绍了解析带有多个参数的命令行选项[getopt?]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我需要我的程序从命令行获取多个参数,语法如下:

I need my program to get several arguments from command line, the syntax is as follows:

getpwd -l user1 user2 ... -L -X -S...

因此,我需要将用户吸引到-l选项的后面.我尝试使用getopt,但运气不佳,仅当将其他选项放在-l之前时,它才起作用:

So, I need to get the users behind the -l option. I tried using getopt, but without much luck, it only works when I place the other options before the -l:

getpwd -L -X -S ... -l user1 user2 ...

我的代码(用于-l和-S):

while((c = getopt(argc, argv, "l:S")) != -1){ switch(c){ case 'l': index = optind-1; while(index < argc){ next = strdup(argv[index]); /* get login */ index++; if(next[0] != '-'){ /* check if optarg is next switch */ login[lcount++] = next; } else break; } break; case 'S': sflag++; /* other option */ break; case ':': /* error - missing operand */ fprintf(stderr, "Option -%c requires an operand\n", optopt); break; case '?': /* error - unknown option */ fprintf(stderr,"Unrecognized option: -%c\n", optopt); break; } }

optopt和optind是extern int.

因此,问题是:我可以使用getopt()函数(或getopt_long())吗?还是我必须编写自己的解析器才能获得所需的内容?

So, the question is: Can I use the getopt() function (or getopt_long()) ? Or do I have to write my own parser to get what I need ?

推荐答案

您的代码实际上非常非常接近工作.您唯一缺少的是getopt仅希望您在-l之后使用一个参数,因此会在-l的第一个参数之后继续命令行解析.由于要退后一步并提取更多参数,因此必须告诉getopt从哪里开始重新解析命令行.

Your code was actually very, very close to working. The only thing you were missing is that getopt only expects you to consume one argument after -l, and therefore continues command line parsing following the first argument to -l. Since you're going behind its back and pulling off more arguments, you have to tell getopt where to start parsing the command line again.

getopt将该信息存储在全局变量optind中.当我添加该行时:

getopt stores that information in the global variable optind. When I added the line:

optind = index - 1;

在l情况下的break;之前,您的代码开始工作.

before the break; in your l case, your code started working.

更多推荐

解析带有多个参数的命令行选项[getopt?]

本文发布于:2023-11-27 21:14:34,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1639627.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:多个   命令行   选项   参数   getopt

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!