簡體   English   中英

命令行參數和結構

[英]Arguments of command line and into struct

我正在用C編寫一個程序,該程序具有多個參數,運行時可以在命令行中鍵入這些參數。 例如:

./proj select row 3 <table.txt

打印行號3。

在我的程序中,我有很多if / else 例如,如果選擇argv [1]而argv [2]是row,則執行此操作,依此類推。 我將其展示給我的老師,並被告知不要使用if-else而是使用結構。 問題是我不知道怎么做。 您能給我一些關於如何開始的簡單建議嗎?

使用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的示例。

有兩點。

首先,我將使用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數組。

當然,您需要填寫其余的代碼。 但這是這個方向的起點和重點。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM