我正在用 c 语言编写一个程序,它接受诸如 --version 、--download 之类的命令行参数。
当我这样做时:
$program --version --download file
程序输出版本并下载文件。但是当我这样做时:
$program --download --version file
程序将 --version
视为 --download
的参数。
我使用了 getopt_long()
函数来解析命令行参数。这是我的代码片段:
while ((ch = getopt_long(argc, argv, "d:g:hv", longoptions, &optindex)) != -1 )
{
switch(ch)
{
case 'd' :
if ( optarg )
printf("Downloading %s...\n" , optarg);
iso(optarg);
break ;
case 'g' :
if ( optarg )
printf("Downloading glug-mirror automation script for %s ...\n", optarg);
getscript(optarg);
break ;
case 'v' :
printf("glug version 1.0.0 ( NIT Hamirpur)\n");
break ;
case 'h' :
usage(status);
break ;
default :
status = 2 ;
usage(status);
}
}
最佳答案
getoptlong()
正在做它应该做的事情。
- 格式字符串
"d:g:hv"
表示参数d
和g
需要一个值。 - 在命令行参数之后指定的任何内容都被视为传递给它的值。
你应该运行你的程序
$program --download file --version
检查这个 detailed example演示使用 getoptlong()
的各个方面。
How
rm
can handle the differing position of its cmd-line params?
显然是因为 rm
的参数(r
、v
等)不接受任何值作为参数。因此 directory
不会传递给它们中的任何一个,而是一个单独的 cmd 行参数。您可以从 source-code of rm 确认这一点.
要为您的程序做类似的事情,您需要将 optstring 修改为 "dghv"
并处理参数 "file"
分别。
关于c - 命令中命令行选项的不同顺序影响我的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18544245/