在C程序中添加一个标志

问题描述 投票:-2回答:2

我写了一个C程序,需要运行看似自定义的标志。我有一个名为“hw3”的可执行文件,我将在终端中使用./hw3来运行。现在我希望我的程序在使用标志运行时获取参数

./hw3 -check

./hw3 -create 3

我已经有一个正常运行的代码来完成这些任务,如何创建一个新的标志来运行该程序?如果你也能提供一些参考,那就更好了。

c compiler-flags
2个回答
2
投票

“flags”只是你在argv中获得的命令行参数。您可以自己检查或使用一些合适的库。对于家庭作业可能更好,更简单,只是为了自己检查。

浏览参数,检查它们是否有效并根据它们进行工作。


0
投票

使用getopt(在linux上)

这是一个example

#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;
}

以下是一些示例,显示了此程序使用不同参数组合打印的内容:

% testopt
aflag = 0, bflag = 0, cvalue = (null)

% testopt -a -b
aflag = 1, bflag = 1, cvalue = (null)

% testopt -ab
aflag = 1, bflag = 1, cvalue = (null)

% testopt -c foo
aflag = 0, bflag = 0, cvalue = foo

% testopt -cfoo
aflag = 0, bflag = 0, cvalue = foo

% testopt arg1
aflag = 0, bflag = 0, cvalue = (null)
Non-option argument arg1

% testopt -a arg1
aflag = 1, bflag = 0, cvalue = (null)
Non-option argument arg1

% testopt -c foo arg1
aflag = 0, bflag = 0, cvalue = foo
Non-option argument arg1

% testopt -a -- -b
aflag = 1, bflag = 0, cvalue = (null)
Non-option argument -b

% testopt -a -
aflag = 1, bflag = 0, cvalue = (null)
Non-option argument -
© www.soinside.com 2019 - 2024. All rights reserved.