【问题标题】:Arguments of command line and into struct命令行参数和结构体
【发布时间】:2014-11-11 23:26:40
【问题描述】:

我正在用 C 语言编写一个程序,它有几个参数,当我运行它时,我可以在命令行中输入这些参数。例如:

./proj select row 3 <table.txt

打印第 3 行。

在我的程序中,我有很多 if/else。例如,如果 argv[1] 是 select 并且 argv[2] 是 row 则执行此操作,依此类推。我把它展示给我的老师,并被告知不要使用 if-else 而是使用结构。问题是我不知道怎么做。你能给我一些关于如何开始的简单建议吗?

【问题讨论】:

  • 您好,我正在用 c 语言编写一个程序,它有几个参数,当我运行它时,我可以在命令行中输入这些参数。例如 ./proj 选择第 3 行
  • 如果没有您尝试做什么的详细信息,或者您想要/需要使用的结构,充其量只能提供帮助。
  • 您应该向我们展示您的程序的相关部分。
  • 该程序使用一个表,它的行和列。 argv[1] 是我想要执行的操作,argv[2] 告诉我是否使用 row/a col/rows/cols 和其他参数是这些行的编号,cols....和 ​​main(int argc, char **argv) 我应该使用 struct 或 enum 或类似的东西来识别程序必须使用的参数......我的代码已经完成并且工作正常,但我必须替换我的“if-else”识别带有结构或枚举的参数

标签: c struct command-line-arguments


【解决方案1】:

使用getopt 处理您的命令行选项。这是一个例子:

http://www.gnu.org/software/libc/manual/html_node/Example-of-Getopt.html

在你的情况下,我认为是这样的:

./proj -r 3 <table.txt

会很好。因此,在您的 getopt while 循环中,您将检查 'r' 参数并存储其值。然后在您的代码中使用该值。比如:

int row_num = -1;
while ((c = getopt (argc, argv, "r:")) != -1)
    switch (c)
      {
      case 'r':
        row_num = optarg;
        break;
      case '?':
        if (optopt == 'r')
          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 ("row_num = %d\n", row_num);

  /* Now use your row_num variable here. */

  return 0;
}

请注意,您也可以将输入文件的名称作为参数,这样您就不必像现在这样通过管道输入它。比如:

./proj -r 3 -f table.txt

您可以在 Internet 上找到更多 getopt 示例。

【讨论】:

    【解决方案2】:

    几点。

    首先我会使用getopt_long() 解析命令行。

    #include <getopt.h>
    
    int opt = 0;
    int opt_index = 0;
    static const char sopts[] = "s:";                    /* Short options */
    static const struct option lopts[] = {               /* Long options  */
                {"select",   required_argument, NULL, 's'},
                {NULL, 0, NULL, 0}
        };
    
    while ((opt = getopt_long(argc, argv, sopts, lopts, &opt_index)) != -1) {
        /* use a switch/case statement to parse the arguments */
    }
    

    其次是在使用结构的情况下。我想到了类似的东西:

    struct opts {
        int num;
        char *select;
    }
    

    以便将行号放入num 并将选择变量(在您的情况下为row)放入select 数组中。

    当然,您需要填写代码的其余部分。但这是朝着这个方向的起点和起点。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-11-30
      • 2016-03-25
      • 1970-01-01
      • 2018-01-25
      • 1970-01-01
      • 2021-12-19
      • 1970-01-01
      相关资源
      最近更新 更多