【问题标题】:Parsing Command Line Options [duplicate]解析命令行选项[重复]
【发布时间】:2015-02-28 22:36:55
【问题描述】:

我写了一些代码,打印命令行帮助:

int main(int argc, char **argv)

    printf("$ ./porfolio6 --help \n"
      "Usage: ./portfolio6 options [FILENAME]\n"

       " -h --help Dsiplay this usage information.\n"
       " -n --num Display my student number.\n"
       " -c --chars Print number of characters in FILENAME.\n"
       " -w --words Print number of words in FILENAME.\n"
       " -l --lines Print number of lines in FILENAME.\n"
       " -f --file FILENAME Read from file.\n");
}

我想知道如何使这些选项真正起作用。目前他们只是打印输出而不做选项要求的事情。

@Apoorv @卡尔·诺鲁姆 我的代码的更新版本是这样的,但我仍然有一些问题,让所有的东西都显示在终端上作为选项

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


void print_usage() {
 printf("Usage: ./portfolio6 options [FILENAME] \n");
}

int main(int arg, char *argc[]) {

int opt =0;
int help = -1, num = -1, chars = -1, words = -1, lines = -1, file = -1;

static struct option long_options[] = {

{"help", required_argument, 0, 'h' },
{"num", required_argument, 0, 'n' },
{"chars", required_argument, 0, 'c' },
{"words", required_argument, 0, 'w' },
{"lines", required_argument, 0, 'l' },
{"file", required_argument, 0, 'f' },
};

 int long_index =0;
while((opt= getopt_long(argc, argv,"hncwl:f:",
             long_options, &long_index )) != -1 {

 switch (opt) {
 case 'h' : /* -h or --h */
 help = 1;
 break;

 case 'n' : /* -n or --n */
 num = 1;
 break;

 case 'c' : /* -c or --c */
 chars = 1;
 break;

 case 'w' : /* -w or --w */
 words = 1;
 break;

 case 'l' : /* -l or --l */
 lines = 1;
 break;

 case 'f' : /* -f or --f */
 file = 1;
 break;
 }
}

【问题讨论】:

标签: c linux


【解决方案1】:

您正在寻找getopt_long(3)。该手册页中有一个示例,涵盖了您需要了解的所有内容。

【讨论】:

  • 如果这是一个答案,而不是评论,也许一个例子是合适的。
  • @TomFenech 再说一遍,这里提供一个示例只不过是粘贴手册页的示例,除非它得到更彻底的评论。
猜你喜欢
  • 2011-03-20
  • 1970-01-01
  • 2012-08-18
  • 1970-01-01
  • 1970-01-01
  • 2013-05-16
  • 2012-01-06
  • 1970-01-01
  • 2015-01-22
相关资源
最近更新 更多