c - c语言中getopt函数的困惑
问题描述
我编写了一个带有 getopt 函数的代码,如下所示:
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<ctype.h>
int main(int argc, char *argv[]){
int result;
opterr=0;
puts("The following parsed outcome to command-line argments by getopt(-a, -b* or -c*):");
while((result=getopt(argc, argv, "ab:c::"))!=-1){
switch(result){
case ':':
printf("getopt returns \'%c\'\toptopt=%c\toptarg=%s\toptind=%d\t", result, optopt, optarg, optind);
break;
case '?':
if(optopt=='b')
fprintf(stderr, "Option -%c requires an argument attached. optarg=%s\toptind=%d\t", optopt, optarg, optind);
else if(isprint(optopt))
fprintf(stderr, "Unknown option \'%c\'.\toptarg=%s\toptind=%d\t", optopt, optarg, optind);
else
fprintf(stderr, "Unknown option character \'%x\'.\toptarg=%s\toptind=%d\t", optopt, optarg, optind);
break;
default:
printf("getopt returns \'%c\'\toptarg=%s\toptind=%d\t", result, optarg, optind);
break;
}
printf("argv[%d]=%s\n", optind, argv[optind]);}
puts("Here is parsed argument values:");
for(result=1; result<argc; result++)
printf("argv[%d]=%s\n", result, argv[result]);
for(; optind<argc; optind++)
printf("No-option argument values: argv[%d]=%s\n", optind, argv[optind]);
return 0;
}
然后我将上面的程序编译成名为parse
. 使用以下命令行参数运行解析:
./parse -ac b
这是输出:
The following parsed outcome to command-line argments by getopt:
getopt returns 'a' optarg=(null) optind=1 argv[1]=-ac
getopt returns 'c' optarg=(null) optind=2 argv[2]=b
Here is parsed argument values:
argv[1]=-ac
argv[2]=b
No-option argument values: argv[2]=b
getopt
我的困惑是为什么在c
遇到. 因为它不是。在我的期望中,假设执行语句c
argv[1] ac
-c
case '?':
解决方案
使用 时getopt
,可以将不带参数的单字符选项与以下选项结合使用。这就是使打字成为可能的原因
ls -lR
即使以下选项带有参数,这也有效。
推荐阅读
- api - 无法解析 HTTP 请求
- javascript - 无法读取 null React 的属性“样式”
- django - Django 嵌套模板
- javascript - Laravel 5.6 如何将 URL 作为 URL 参数传递?
- c++builder - 窗口屏幕应用程序行为,如屏幕键盘
- google-analytics - 谷歌分析 - 产品列表视图 - 谷歌如何计算指标?
- servicenow - ServiceNow 个人开发者实例启用了 SecurityOperations 插件?
- android - firebase 中创建帐户的结果为 true,但未在 firebase 控制台中添加
- php - 如何在不使用依赖注入器的情况下注册伏特引擎?
- javascript - ChartsJS 获取工具提示的数据/数据集标签的值