2012-12-03 11 views
7

私は現在、内部開発チームが使用するコマンドラインヘルパーユーティリティをいくつか作成することになっています。しかし、私はUNIXのコマンドラインツールを作成するためのベストプラクティスについて知りたい。私は、パラメータを読み、それに応じてメッセージを表示する方法の例については、git source codeを表示しようとしました。しかし、私はツールを作成するための明確なテンプレートを探しています。パラメータを安全に読み込み、ユーザが間違ったパラメータを入力すると、標準の "ヘルプ"メッセージを表示します。--helpヘルプメッセージを表示します。 -abcFGH--parameterを読み込み、渡されたパラメータに基づいてどのプロセスが開始するかを切り替えるための標準ライブラリはありますか?C/C++でunix/linuxコマンドラインツールを作成するベストプラクティスは何ですか?

コマンドライン:

git 

または

git --help 

出力:

usage: git [--version] [--exec-path[=<path>]] [--html-path] [--man-path] [--info-path] 
     [-p|--paginate|--no-pager] [--no-replace-objects] [--bare] 
     [--git-dir=<path>] [--work-tree=<path>] [--namespace=<name>] 
     [-c name=value] [--help] 
     <command> [<args>] 
... 

コマンドライン:

MyTool CommandName --CommandArgs 

出力:

、特定のコマンドがないものは何でも。


は私がこれまでに取り組んできた何:

コード:

コード:

int main(int argc, char **argv) 
{ 
    MagicParameters magicParameters = new MagicParameters(argv); 
    switch(magicParameters[1]) 
    { 
     case command1: 
      Command1(); 
      break; 
     case ... 

     case help: 
     default: 
      HelpMessage(); 
      break; 
    } 
} 
次のようになり理想的である何

int main(int argc, char **argv) 
{ 
    if(argc < 2) 
    helpMessage(); 
    char* commandParameter = argv[1]; 
    if (strncmp(argv [1],"help", strlen(commandParameter)) == 0) 
     helpMessage(); 
    else if (strncmp(argv [1],"pull", strlen(commandParameter)) == 0) 
     pull(); 
    else 
     helpMessage(); 
} 
+2

は、あなたが() ''のgetoptで見たことがありますか?もしそうでなければ、あなたが望むものである 'getopt_long'をチェックし、目にも簡単です。 –

答えて

8

のgetopt_long()はここで、あなたが探しているもので、最も簡単な使い方の例です:

static const struct option opts[] = { 
     {"version", no_argument, 0, 'v'}, 
     {"help",  no_argument, 0, 'h'}, 
     {"message", required_argument, 0, 'm'}, 
     /* And so on */ 
     {0,  0,     0, 0 } /* Sentiel */ 
    }; 
    int optidx; 
    char c; 

    /* <option> and a ':' means it's marked as required_argument, make sure to do that. 
    * or optional_argument if it's optional. 
    * You can pass NULL as the last argument if it's not needed. */ 
    while ((c = getopt_long(argc, argv, "vhm:", opts, &optidx)) != -1) { 
     switch (c) { 
      case 'v': print_version(); break; 
      case 'h': help(argv[0]); break; 
      case 'm': printf("%s\n", optarg); break; 
      case '?': help(argv[0]); return 1;    /* getopt already thrown an error */ 
      default: 
       if (optopt == 'c') 
        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; 
     } 
    } 
    /* Loop through other arguments ("leftovers"). */ 
    while (optind < argc) { 
     /* whatever */; 
     ++optind; 
    } 
2

getoptライブラリを見てください。

関連する問題