C Language                
            コマンドライン引数
        
        
            
    サーチ…
構文
- int main(int argc、char * argv [])
パラメーター
| パラメータ | 詳細 | 
|---|---|
| argc | 引数count - コマンドラインからプログラムに与えられたスペースで区切られた引数の数とプログラム名自体に初期化されます。 | 
| argv | 引数vector  - コマンドラインで与えられた引数(およびプログラム名)を含む char-pointers(文字列)の配列に初期化されます。 | 
備考
 「ホストされた環境」(通常のタイプ - 「フリースタンド環境」とは対照的に)で動作するACプログラムは、 main機能を備えていなければなりません。伝統的には次のように定義されています。 
int main(int argc, char *argv[])
 argvは、 char **argvとして定義することもできます。行動は同じです。また、パラメータ名は関数内のローカル変数であるため変更できますが、 argcとargvは従来のものであり、これらの名前を使用する必要があります。 
コードが引数を使用しないmain関数については、 int main(void)使用してください。 
両方のパラメータは、プログラムの開始時に初期化されます。
-  argcは、コマンドラインからプログラムに与えられたスペースで区切られた引数の数とプログラム名自体に初期化されます。
-  argvは、コマンドラインで与えられた引数(およびプログラム名)を含むchar-pointers(文字列)の配列です。
- いくつかのシステムはコマンドライン引数を "シェルの中で"展開しますが、他のものは展開しません。 Unixでは、ユーザがmyprogram *.txtと入力すると、プログラムはテキストファイルのリストを受け取ります。 Windowsでは文字列 "*.txt"を受け取ります。
注意: argvを使用する前に、 argcの値をチェックする必要があります。理論的には、 argcは0になり、 argcが0の場合、引数はなく、 argv[0] ( argv[argc]相当)はNULLポインタです。この問題に遭遇した場合、ホストされた環境では異常なシステムになります。同様に、非常に珍しいことですが、プログラム名についての情報がないこともありえます。その場合、 argv[0][0] == '\0' - プログラム名は空であるかもしれません。 
次のようにプログラムを開始するとします。
./some_program abba banana mamajam
 argcは4に等しく、コマンドライン引数は次のようになります。 
- プログラム名がホスト環境から利用可能である場合、 argv[0]は"./some_program"(プログラム名)を指します。それ以外の場合は空の文字列""返します。
-  argv[1]は"abba"指します。
-  argv[2]は"banana"指します。
-  argv[3]は"mamajam"指します。
-  argv[4]には値NULLが含まれていNULL。
また、標準からの完全な引用については、CおよびC ++でmain()返す必要があるのも見てください。 
コマンドライン引数の表示
引数を受け取ったら、次のようにそれらを印刷することができます:
int main(int argc, char **argv)
{
    for (int i = 1; i < argc; i++)
    {
        printf("Argument %d: [%s]\n", i, argv[i]); 
    }
}
ノート
-  argvパラメータは、char *argv[]として定義することもできます。
-  argv[0]は 、(プログラムの実行方法に応じて)プログラム名自体が含まれることがあります。最初の "実際の"コマンドライン引数はargv[1]にあり、これがループ変数iが1に初期化される理由です。
-  print文では、 argv[i]代わりに*(argv + i)使うことができます。同じことが評価されますが、より冗長です。
- 引数の値を囲む角かっこは、開始と終了を識別するのに役立ちます。引数に後続の空白、改行、キャリッジリターン、またはその他の奇妙な文字がある場合、これは非常に重要です。このプログラムのいくつかの亜種は、引数リストに実際に含まれているものを理解する必要がある場合にシェルスクリプトをデバッグするのに便利なツールです(しかし、ほぼ同等の単純なシェルの代替があります)。
引数をプログラムに出力し、整数値に変換する
次のコードは、引数をプログラムに出力し、コードは各引数を数値に変換しようとします( long )。 
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <limits.h>
int main(int argc, char* argv[]) {
    for (int i = 1; i < argc; i++) {
        printf("Argument %d is: %s\n", i, argv[i]);
        errno = 0;
        char *p;
        long argument_numValue = strtol(argv[i], &p, 10);
        if (p == argv[i]) {
            fprintf(stderr, "Argument %d is not a number.\n", i);
        }
        else if ((argument_numValue == LONG_MIN || argument_numValue == LONG_MAX) && errno == ERANGE) {
            fprintf(stderr, "Argument %d is out of range.\n", i);
        }
        else {
            printf("Argument %d is a number, and the value is: %ld\n",
                   i, argument_numValue);
        }
    }
    return 0;
}
参考文献:
GNU getoptツールを使う
アプリケーションのコマンドラインオプションは、C言語によるコマンドライン引数とは異なる扱いを受けません。それらは、LinuxまたはUnix環境では伝統的にダッシュ( - )で始まる引数です。 
LinuxやUnix環境でglibcを使うと、 getoptツールを使って残りの引数からコマンドラインオプションを簡単に定義、検証、解析することができます。
これらのツールは、オプションがGNUコーディング標準に従ってフォーマットされることを期待しています。これはPOSIXがコマンドラインオプションの形式のために指定したものの拡張です。
次の例は、GNU getoptツールを使用してコマンドラインオプションを処理する方法を示しています。
#include <stdio.h>
#include <getopt.h>
#include <string.h>
/* print a description of all supported options */
void usage (FILE *fp, const char *path)
{
    /* take only the last portion of the path */
    const char *basename = strrchr(path, '/');
    basename = basename ? basename + 1 : path;
    fprintf (fp, "usage: %s [OPTION]\n", basename);
    fprintf (fp, "  -h, --help\t\t"
                 "Print this help and exit.\n");
    fprintf (fp, "  -f, --file[=FILENAME]\t"
                 "Write all output to a file (defaults to out.txt).\n");
    fprintf (fp, "  -m, --msg=STRING\t"
                 "Output a particular message rather than 'Hello world'.\n");
}
/* parse command-line options and print message */
int main(int argc, char *argv[])
{
    /* for code brevity this example just uses fixed buffer sizes for strings */
    char filename[256] = { 0 };
    char message[256] = "Hello world";
    FILE *fp;
    int help_flag = 0;
    int opt;
    /* table of all supported options in their long form.
     * fields: name, has_arg, flag, val
     * `has_arg` specifies whether the associated long-form option can (or, in
     * some cases, must) have an argument. the valid values for `has_arg` are
     * `no_argument`, `optional_argument`, and `required_argument`.
     * if `flag` points to a variable, then the variable will be given a value
     * of `val` when the associated long-form option is present at the command
     * line.
     * if `flag` is NULL, then `val` is returned by `getopt_long` (see below)
     * when the associated long-form option is found amongst the command-line
     * arguments.
     */
    struct option longopts[] = {
        { "help", no_argument, &help_flag, 1 },
        { "file", optional_argument, NULL, 'f' },
        { "msg", required_argument, NULL, 'm' },
        { 0 }
    };
    /* infinite loop, to be broken when we are done parsing options */
    while (1) {
        /* getopt_long supports GNU-style full-word "long" options in addition
         * to the single-character "short" options which are supported by
         * getopt.
         * the third argument is a collection of supported short-form options.
         * these do not necessarily have to correlate to the long-form options.
         * one colon after an option indicates that it has an argument, two
         * indicates that the argument is optional. order is unimportant.
         */
        opt = getopt_long (argc, argv, "hf::m:", longopts, 0);
        if (opt == -1) {
            /* a return value of -1 indicates that there are no more options */
            break;
        }
        switch (opt) {
        case 'h':
            /* the help_flag and value are specified in the longopts table,
             * which means that when the --help option is specified (in its long
             * form), the help_flag variable will be automatically set.
             * however, the parser for short-form options does not support the
             * automatic setting of flags, so we still need this code to set the
             * help_flag manually when the -h option is specified.
             */
            help_flag = 1;
            break;
        case 'f':
            /* optarg is a global variable in getopt.h. it contains the argument
             * for this option. it is null if there was no argument.
             */
            printf ("outarg: '%s'\n", optarg);
            strncpy (filename, optarg ? optarg : "out.txt", sizeof (filename));
            /* strncpy does not fully guarantee null-termination */
            filename[sizeof (filename) - 1] = '\0';
            break;
        case 'm':
            /* since the argument for this option is required, getopt guarantees
             * that aptarg is non-null.
             */
            strncpy (message, optarg, sizeof (message));
            message[sizeof (message) - 1] = '\0';
            break;
        case '?':
            /* a return value of '?' indicates that an option was malformed.
             * this could mean that an unrecognized option was given, or that an
             * option which requires an argument did not include an argument.
             */
            usage (stderr, argv[0]);
            return 1;
        default:
            break;
        }
    }
    if (help_flag) {
        usage (stdout, argv[0]);
        return 0;
    }
    if (filename[0]) {
        fp = fopen (filename, "w");
    } else {
        fp = stdout;
    }
    if (!fp) {
        fprintf(stderr, "Failed to open file.\n");
        return 1;
    }
    fprintf (fp, "%s\n", message);
    fclose (fp);
    return 0;
}
これはgccでコンパイルすることができます: 
gcc example.c -o example
 3つのコマンドラインオプション( --help 、-- --file 、-- --msg )を--msgます。すべてが「短い形式」( -h 、 -f 、および-m )も持っています。 "file"と "msg"オプションはどちらも引数を受け入れます。 "msg"オプションを指定した場合、その引数は必須です。 
オプションの引数は次のように書式設定されます。
-  --option=value(長い形式のオプションの場合)
-  -ovalue-o"value"または-o"value"(短縮形オプションの場合)