【发布时间】:2014-12-19 22:49:58
【问题描述】:
因此,我从高处和低处搜索了这个问题的答案,我所能找到的只是有人在 2 年前提出了同样的问题,但从未真正得到回答 (option followed by a option in getopt [where the earlier option was expecting a value])。
目前,我正在编写一个应该接受命令行选项和参数的程序。
该命令应该创建和操作通过命令行提供的存档文件。我正在使用getopt()。该命令的用法是oscar [options] [archive-file] [member files],但是有些选项不需要参数。例如“-v”标志,它代表详细,并且只会导致文件中的其他操作吐出比默认更多的打印语句。
这是我使用 getopt() 的代码:
//declaring some variables to be used by getopt
18 extern char *optarg; //pointer to options that require an argument
19 extern int optind; //index into main()'s argument list (argv[])
20
21 int getOptReturn = 0; //int that stores getopt's return (used to check if it is done parsing)
22 int error = 0; //flag for '?' case if getopt doesn't receive proper input
23
24 //flags for all the options
25 int a_flag, A_flag, v_flag, C_flag, d_flag, e_flag, h_flag,
26 m_flag, o_flag, t_flag, T_flag, E_flag, V_flag, u_flag = 0;
27
28 int i; //for loops index
29
30 char *aname;
31
32 //while parsing options
33 while((getOptReturn = getopt(argc, argv, "a:A:Cd:e:E:hm:otTu:vV")) != -1)
34 {
35 //debugging
36 printf("optind: %d, option: %c, optarg: %s \n", optind, argv[optind], optarg);
37 printf("%d\n", argc);
38
39 //switch options and set appropriate flags
40 switch(getOptReturn)
41 {
42 case 'a':
43 printf("-a option received\n");
44 //turn add flag on
45 a_flag = 1;
46 aname = optarg;
47 printf("argument supplied to -a: %s \n", aname);
48 break;
49 case 'A':
50 printf("-A option received\n");
51 //turn add all flag on
52 A_flag = 1;
53 aname = optarg;
54 printf("argument supplied to -A: %s \n", aname);
55 break;
56 case 'v':
57 printf("-v option received\n");
58 //turn verbose flag on
59 v_flag = 1;
60 printf("verbose flag turned on!\n");
61 break;
现在我面临的问题是,我传递选项字符的顺序在不应该传递的时候很重要。
例如:
如果我用./oscar -va archive 调用函数,代码正常运行,v 导致 v 标志打开,a 使用archive 作为参数处理,因为我需要a getopt() 内部的一个参数。
但是,如果我使用./oscar -av archive 调用该函数,则代码将读取a 并将v 作为其必需的参数,而不是将v 作为选项读取并使用archive 作为@987654336 的参数@。
有什么方法可以告诉getopt() 跳过 argv[] 中的其他选项值,以便我可以从命令行使用各种组合调用该函数,而不必担心顺序,例如:
./oscar -avo archive file1 file2 file3...
./oscar -a A v archive file1 file2...
【问题讨论】:
-
哎呀,很抱歉编辑不好。我不小心删除了问题中的所有数字,而不仅仅是行号。
-
这是 POSIX 指南指定的程序选项的标准行为。 “一个或多个不带选项参数的选项,后跟最多一个带有选项参数的选项,当分组在一个'-'分隔符后面时应该被接受。”不要打破标准。
-
嗯,我明白了。我想出了如何绕过它并使用 optind 和 argc 手动处理它,但感谢您的回答。这真的让我很烦。
-
我并不想听起来过于挑剔,但请告诉我这并不严重。我不想输入
-a Archive并将其解析为选项-a,选项-A,参数-a“rc”,选项-h,参数-A“i”,选项@ 987654346@,选项-e。我希望它是选项-a,然后是它的参数“存档”。如果这不仅仅是一个选项解析的练习,我希望永远不要使用你的程序,因为我会努力弄清楚如何正确传递命令行选项。getopt以它的方式工作是有原因的。请不要破坏用户的预期行为。 -
非常严重。这是我的操作系统课的作业,这就是教授希望我们使用该程序的方式。使用他的示例程序,您可以先使用必需的选项调用它,它仍然可以像魅力一样工作。我的教授还说他使用了
getopt,所以我只是想知道。
标签: c command-line getopt command-line-arguments