Con*_*lor 14 c arguments getopt getopt-long argv
我正在C中创建一个处理大量命令行参数的小程序,所以我决定使用getopt为我排序.
但是,我希望两个非选项参数(源文件和目标文件)是必需的,因此在调用程序时必须将它们作为参数,即使没有标志或其他参数.
这是我用标志处理参数的简化版本:
while ((c = getopt(argc, argv, "i:d:btw:h:s:")) != -1) {
switch (c) {
case 'i': {
i = (int)atol(optarg);
}
case 'd': {
d = (int)atol(optarg);
}
case 'b':
buf = 1;
break;
case 't':
time = 1;
break;
case 'w':
w = (int)atol(optarg);
break;
case 'h':
h = (int)atol(optarg);
break;
case 's':
s = (int)atol(optarg);
break;
default:
break;
}
}
Run Code Online (Sandbox Code Playgroud)
如何编辑它以便还处理非选项参数?
我还希望能够在选项之前或之后获得非选项,那么如何处理呢?
Kla*_*äck 24
getopt设置optind变量以指示下一个参数的位置.
选项循环后添加类似于此的代码:
if (argv[optind] == NULL || argv[optind + 1] == NULL) {
printf("Mandatory argument(s) missing\n");
exit(1);
}
Run Code Online (Sandbox Code Playgroud)
编辑:
如果你想在常规参数后允许选项,你可以做类似的事情:
while (optind < argc) {
if ((c = getopt(argc, argv, "i:d:btw:h:s:")) != -1) {
// Option argument
switch (c) {
case 'i': {
i = (int)atol(optarg);
}
case 'd': {
d = (int)atol(optarg);
}
case 'b':
buf = 1;
break;
case 't':
time = 1;
break;
case 'w':
w = (int)atol(optarg);
break;
case 'h':
h = (int)atol(optarg);
break;
case 's':
s = (int)atol(optarg);
break;
default:
break;
}
else {
// Regular argument
<code to handle the argument>
optind++; // Skip to the next argument
}
}
Run Code Online (Sandbox Code Playgroud)
可以在这里找到非常好的例子:GNU Libc代码:
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int
main (int argc, char **argv)
{
int aflag = 0;
int bflag = 0;
char *cvalue = NULL;
int index;
int c;
opterr = 0;
while ((c = getopt (argc, argv, "abc:")) != -1)
switch (c)
{
case 'a':
aflag = 1;
break;
case 'b':
bflag = 1;
break;
case 'c':
cvalue = optarg;
break;
case '?':
if (optopt == 'c')
fprintf (stderr, "Option -%c requires an argument.\n", optopt);
else if (isprint (optopt))
fprintf (stderr, "Unknown option `-%c'.\n", optopt);
else
fprintf (stderr,
"Unknown option character `\\x%x'.\n",
optopt);
return 1;
default:
abort ();
}
printf ("aflag = %d, bflag = %d, cvalue = %s\n",
aflag, bflag, cvalue);
for (index = optind; index < argc; index++)
printf ("Non-option argument %s\n", argv[index]);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
它允许在参数之前和之后有选项.我编译并运行测试示例:
$ ./a.out aa ff bb -a -ctestparam hello
aflag = 1, bflag = 0, cvalue = testparam
Non-option argument aa
Non-option argument ff
Non-option argument bb
Non-option argument hello
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
22109 次 |
| 最近记录: |