从命令行将参数传递到 C 程序

问题描述 投票:0回答:6

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

例如,

./myprogram 42 -b -s

那么程序会将数字 42 存储为 int 并根据它获得的参数(如 -b 或 -s)执行代码的某些部分。

c linux arguments
6个回答
43
投票

您可以使用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;
 }

29
投票

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

可以在网上找到更多信息,例如这篇主要文章的论点。


10
投票

考虑使用

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

相关:


7
投票

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


5
投票

除了

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

来自libc手册

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

但我总是对标准感到满意

getopt

注意GNU

getopt
getopt_long
是 GNU LGPL。


4
投票

其他人都击中了这个的头:

  • 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);

然后主要的第一件事:

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

或者您可以使用C/UNIX 的参数解析助手中建议的解决方案之一。

© www.soinside.com 2019 - 2024. All rights reserved.