我开始自学 C。我在这里和那里遇到了一些颠簸,但现在我被 getOpt()
难住了。给我带来麻烦的主要事情是当我试图使某些标志依赖于其他标志时。例如我希望这些工作:
./myfile -a -b -c blue
但是没有-a,其他选项都无法工作。因此 ./myfile -b -c purple
将无效。 getopt 是否有可能处理这种“标志相关”标准?我该怎么做呢?其次,比方说,无论传递什么旗帜,都必须伴随着一种颜色。
所以 ./myfile -a -b green
和 ./myfile red
都是有效的。我知道这一切都在 getOpt() 的选项参数内(目前设置为看起来像这样的“abc”),但是我如何在不执行“a:b:c:”的情况下为每个实例设置一个参数: "因为如果没有传递标志,这将不包括强制性颜色。
最佳答案
这是 getopt
的示例(来自联机帮助页):
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
int
main (int argc, char *argv[])
{
int flags, opt;
int nsecs, tfnd;
nsecs = 0;
tfnd = 0;
flags = 0;
while ((opt = getopt (argc, argv, "nt:")) != -1)
{
switch (opt)
{
case 'n':
flags = 1;
break;
case 't':
nsecs = atoi (optarg);
tfnd = 1;
break;
default: /* '?' */
fprintf (stderr, "Usage: %s [-t nsecs] [-n] name\n", argv[0]);
exit (EXIT_FAILURE);
}
}
printf ("flags=%d; tfnd=%d; optind=%d\n", flags, tfnd, optind);
if (optind >= argc)
{
fprintf (stderr, "Expected argument after options\n");
exit (EXIT_FAILURE);
}
printf ("name argument = %s\n", argv[optind]);
/* Other code omitted */
exit (EXIT_SUCCESS);
}
请注意,您需要添加一些声明和一个 main()
函数才能使其正常工作。
您可以看到上面的示例 n
是一个标志,并且像您的 b
选项一样工作。上面的 t
选项接受一个参数,并且像您的 c
选项一样工作。如果你想有一个 a
选项也是一个标志,你可以使 getopt
参数 "abf:"
(即添加一个 a
in without a colon), and a stanza to the switch
like this:
case 'a':
aflag = 1;
break;
首先将 aflag
设置为 0。最后,您将检查在未设置 aflag
的情况下传递其他选项的非法情况。
总而言之,它看起来像这样:
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
int
main (int argc, char *argv[])
{
int flags, opt;
int nsecs, tfnd;
int aflag;
nsecs = 0;
tfnd = 0;
flags = 0;
aflag = 0;
while ((opt = getopt (argc, argv, "ant:")) != -1)
{
switch (opt)
{
case 'a':
aflag = 1;
break;
case 'n':
flags = 1;
break;
case 't':
nsecs = atoi (optarg);
tfnd = 1;
break;
default: /* '?' */
fprintf (stderr, "Usage: %s [-t nsecs] [-n] name\n", argv[0]);
exit (EXIT_FAILURE);
}
}
printf ("flags=%d; tfnd=%d; optind=%d\n", flags, tfnd, optind);
if (optind >= argc)
{
fprintf (stderr, "Expected argument after options\n");
exit (EXIT_FAILURE);
}
if (!aflag && (flags || tfnd))
{
fprintf (stderr, "Must specify a flag to use n or t flag\n");
exit (EXIT_FAILURE);
}
printf ("name argument = %s\n", argv[optind]);
/* Other code omitted */
exit (EXIT_SUCCESS);
}
关于使用 getopt() : giving command line flags criteria 进行 C 编程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28139701/