【问题标题】:Pass arguments into C program from command line从命令行将参数传递给 C 程序
【发布时间】:2010-10-04 15:24:00
【问题描述】:

所以我在 Linux 中,我想让一个程序在你从命令行执行它时接受参数。

例如,

./myprogram 42 -b -s

然后程序会将数字 42 存储为 int 并根据 -b 或 -s 之类的参数执行某些代码部分。

【问题讨论】:

  • 命令行的规范格式在诸如“42”之类的任何非选项参数之前传递诸如“-b”和“-s”之类的选项参数。因此,标准的正统命令行格式将是“./myprogram -b -s 42”。避免偏离该标准。 [...更多在下一条评论...]
  • 参见opengroup.org/onlinepubs/009695399/toc.htm POSIX 标准基本定义的第 12 节(实用程序约定)。
  • @Jonathan Leffler:顺序无关紧要。无论顺序如何,getopt_long 函数都会做正确的事情。看我的回答。

标签: c linux arguments


【解决方案1】:

你可以使用getopt

 #include <ctype.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <unistd.h>

 int
 main (int argc, char **argv)
 {
   int bflag = 0;
   int sflag = 0;
   int index;
   int c;

   opterr = 0;

   while ((c = getopt (argc, argv, "bs")) != -1)
     switch (c)
       {
       case 'b':
         bflag = 1;
         break;
       case 's':
         sflag = 1;
         break;
       case '?':
         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 ("bflag = %d, sflag = %d\n", bflag, sflag);

   for (index = optind; index < argc; index++)
     printf ("Non-option argument %s\n", argv[index]);
   return 0;
 }

【讨论】:

  • 他/她不应该先了解“主要论点通过”吗? ;)
  • 它将在 Linux 上运行,因为 getopt() 函数是 GNU getopt() 并且您通常不会在环境中设置 POSIXLY_CORRECT,然后 GNU getopt() 在“文件”参数之前处理选项参数,即使它们遵循示例中的文件参数。在 POSIX 平台上,它不起作用....
  • ....因为 42 将阻止 -b 和 -s 选项被解释为选项。当然,命令行的设计也很糟糕。我会在问题的 cmets 中注明。
  • @Jonathan:这个问题确实有标签linux。因此 GNU getopt() 示例在这里是合适的。
  • @J F Sebastian - 是的,它确实有一个 Linux 标签;这就是为什么它得到我的支持。命令行的结构和参数排序不应该依赖于这个怪癖;好吧,我仍然必须在其他平台上工作,而 GNU getopt 在其他平台上不是标准的(尽管它可用)。
【解决方案2】:

在 C 中,这是使用传递给 main() 函数的参数来完成的:

int main(int argc, char *argv[])
{
    int i = 0;
    for (i = 0; i < argc; i++) {
        printf("argv[%d] = %s\n", i, argv[i]);
    }
    return 0;
}

更多信息可以在网上找到,比如这篇Arguments to main文章。

【讨论】:

  • 对不起 - 这不是一个非常好的外部参考。声明中有一个错误:“argv 参数的声明通常是新手程序员第一次遇到指向指针数组的指针,并且可以证明是令人生畏的”(argv 是指针数组,而不是指向指针数组的指针)。
  • 此外,下一页显示了一个临时选项解析器,而不是使用标准的 getopt() 或 getopt_long() 解析器——这简直是个坏建议。不 - 这不是一个很好的参考。
  • 在 C 中,对数组的引用是地址,就像指针是地址一样。因此,argv 既可以称为“数组”,也可以称为“指向数组的指针”。这是 C 语言的美丽简洁之一,也是令人困惑的地方之一。
【解决方案3】:

考虑使用getopt_long()。它允许任何组合的短期和长期期权。

#include <stdio.h>
#include <stdlib.h>
#include <getopt.h>

/* Flag set by `--verbose'. */
static int verbose_flag;

int
main (int argc, char *argv[])
{
  while (1)
    {
      static struct option long_options[] =
    {
      /* This option set a flag. */
      {"verbose", no_argument,       &verbose_flag, 1},
      /* These options don't set a flag.
         We distinguish them by their indices. */
      {"blip",    no_argument,       0, 'b'},
      {"slip",    no_argument,       0, 's'},
      {0,         0,                 0,  0}
    };
      /* getopt_long stores the option index here. */
      int option_index = 0;

      int c = getopt_long (argc, argv, "bs",
               long_options, &option_index);

      /* Detect the end of the options. */
      if (c == -1)
    break;

      switch (c)
    {
    case 0:
      /* If this option set a flag, do nothing else now. */
      if (long_options[option_index].flag != 0)
        break;
      printf ("option %s", long_options[option_index].name);
      if (optarg)
        printf (" with arg %s", optarg);
      printf ("\n");
      break;
    case 'b':
      puts ("option -b\n");
      break;
    case 's':
      puts ("option -s\n");
      break;
    case '?':
      /* getopt_long already printed an error message. */
      break;

    default:
      abort ();
    }
    }

  if (verbose_flag)
    puts ("verbose flag is set");

  /* Print any remaining command line arguments (not options). */
  if (optind < argc)
    {
      printf ("non-option ARGV-elements: ");
      while (optind < argc)
    printf ("%s ", argv[optind++]);
      putchar ('\n');
    }

  return 0;
}

相关:

【讨论】:

    【解决方案4】:

    看看getopt库;这几乎是这类事情的黄金标准。

    【讨论】:

      【解决方案5】:

      除了getopt(),您还可以考虑使用argp_parse()(同一库的替代接口)。

      来自libc manual

      getopt 更标准( 它的仅空头选项版本是 POSIX 标准的一部分),但使用 argp_parse 通常更容易,对于 非常简单和非常复杂的选项 结构,因为它做的更多 为你做肮脏的工作。

      但我总是对标准的getopt 感到满意。

      注意GNU getoptgetopt_long 是 GNU LGPL。

      【讨论】:

      • "getopt 是 GNU LGPL":这取决于 getopt。它已经实施了几次。 Mac OS X 中的那个是 BSD 许可的。
      • AT&T 在 80 年代中期发布了一个进入公共领域,或者非常接近公共领域的东西。 D McKee 的观点非常有效——GNU getopt() [和 getopt_long()] 是 LGPL(或者,旧版本是 GPL);并非所有版本的 getopt() 都是 GPL 或 LGPL。
      【解决方案6】:

      其他人打过这个:

      • main(int argc, char **argv) 的标准参数让您可以直接访问命令行(在它被 shell 破坏和标记之后)
      • 有非常标准的命令行解析工具:getopt()getopt_long()

      但正如您所见,使用它们的代码有点冗长,而且非常符合规范。我通常会用以下方式将其推到视野之外:

      typedef
      struct options_struct {
         int some_flag;
         int other_flage;
         char *use_file;
      } opt_t;
      /* Parses the command line and fills the options structure, 
       * returns non-zero on error */
      int parse_options(opt_t *opts, int argc, char **argv);
      

      然后是 main 中的第一件事:

      int main(int argc, char **argv){
         opt_t opts;
         if (parse_options(&opts,argc,argv)){
            ...
         } 
         ...
      }
      

      或者您可以使用Argument-parsing helpers for C/UNIX 中建议的解决方案之一。

      【讨论】:

        猜你喜欢
        • 2013-07-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-05-20
        相关资源
        最近更新 更多