c - 以任意顺序使用选项和参数解析命令行
问题描述
我很难考虑从命令行参数读取输入文件的方法,而参数可以以不同的方式排序。
例如:
./a.out -d mazeData1.txt would read the input file from argv[2]
但也可以订购命令行参数:
./a.out mazeData1.txt -d
^ 现在输入文件在 argv[1] 中
怎么能找到这样的输入文件?
解决方案
这是 getopt() 的第一种简单方法。请参阅手册 (man 3 getopt) 了解更多信息:
#include <unistd.h>
#include <stdio.h>
int main(int ac, char *av[])
{
int opt;
extern int optind;
while ((opt = getopt(ac, av, "d")) != -1) {
switch(opt) {
case 'd': {
printf("-%c option\n", opt);
}
break;
default: {
printf("Unknown option\n");
return 1;
}
}
}
if (av[optind]) {
printf("First non option parameter: %s\n", av[optind]);
}
return 0;
}
推荐阅读
- c# - 如果从示例表中读取测试数据,源标签的意义何在?我收到错误“场景大纲...没有定义示例”
- angular - 来自rest api的角度材料数据表
- php - 是否有某种方法可以“欺骗”单个 PHP 脚本,使其认为系统时钟/日期与实际不同?
- scala - Spark - 替换列值 - 正则表达式模式值具有斜线值 - 如何处理它?
- c# - X-Robots-Tag 的格式不可用_after
- firebase - Firestore)如何在更新数据字段后更新recyclerview
- regex - 具有相等和不相等正则表达式的 nginx 位置
- spring - 拥有的实体实例不再引用具有 cascade="all-delete-orphan" 的集合 - Spring 和 Lombok
- arch - 尝试为 yay 运行 makepkg -sic 时收到错误 1 消息
- javascript - 从另一个数组中的数组中查找值,然后匹配第二个值 Google Apps Script Javascript JSON API