我正在编写一个使用*argv[]
参数的简单代码。我想知道我是否可以使用getopt()
函数来实现以下目的。
./myprogram -a PATH
./myprogram PATH
除了PATH
之外,该程序可以仅采用/usr/tmp
(例如-a
)或采用PATH
选项。 getopt()
可以用于这个州吗?如果可以,怎么样?
该程序可以只采取
PATH
(例如/usr/tmp
)或除了PATH
之外选择。getopt()
可以用于这个州吗?如果可以,怎么样?
当然。我不确定你在哪里看到潜在的问题,除非你不理解POSIX和getopt()
在选项和论点之间的区别。它们是相关的,但根本不是相同的。
getopt()
适用于实际上没有指定选项的情况,并且它允许您访问非选项参数,例如PATH
似乎适合您,无论指定了多少选项。通常的使用模型是在循环中调用getopt()
,直到它返回-1
以指示命令行中没有更多选项可用。在每一步,全局变量optind
变量提供要处理的下一个argv
元素的索引,并且在getopt()
(first)返回-1之后,optind
提供第一个非选项参数的索引。在你的情况下,那将是你期望找到PATH
的地方。
int main(int argc, char *argv[]) {
const char options[] = "a";
_Bool have_a = 0;
char *the_path;
int opt;
do {
switch(opt = getopt(argc, argv, options)) {
case -1:
the_path = argv[optind];
// NOTE: the_path will now be null if no path was specified,
// and you can recognize the presence of additional,
// unexpected arguments by comparing optind to argc
break;
case 'a':
have_a = 1;
break;
case '?':
// handle invalid option ...
break;
default:
// should not happen ...
assert(0);
break;
}
} while (opt >= 0);
}
使用"a"
的optstring允许-a
的参数作为标志。
optind
帮助检测到只有一个额外的参数存在。
该程序可以作为./program -a path
或./program path
执行
#include <stdio.h>
#include <unistd.h>
int main(int argc, char **argv)
{
char op = ' ';//default value
int opt;
while ((opt = getopt(argc, argv, "a")) != -1)//optstring allows for -a argument
{
switch (opt)
{
case 'a':
op = 'a';//found option, set op
break;
default:
fprintf(stderr, "%s: unknown option %c\n", argv[0], optopt);
return 1;
}
}
if ( optind + 1 != argc)//one argument allowed besides optstring values
{
fprintf(stderr, "Usage: %s [-a] PATH\n", argv[0]);
return 1;
}
printf("%s %c\n", argv[optind], op);
return 0;
}