1

私はこのようなプログラムを持っています:

./server

この使用法は次のとおりです。

Usage : 
-p  Port to use (4242 by default)
-x  Map width (20)
-y  Map height (20)
-n  Team name (name_team1 name_team2)
-c  Players per team
-t  Delay 

このコードですべてのオプションを解析できました:

int parse_cmd(int argc, char **argv, t_args *a)
{
    char ch;

    if (argv[1] && argv[1][0] != '-')
        usage();
    while ((ch = getopt(argc, argv, "p:x:y:n:c:t:")) != -1)
    {
        if (ch == 'p')
            a->port = atoi(optarg);
        else if (ch == 'x')
            a->x = atoi(optarg);
        else if (ch == 'y')
            a->y = atoi(optarg);
        else if (ch == 'n')
            a->teams = name_teams(optarg);
        else if (ch == 'c')
            a->size = atoi(optarg);
        else if (ch == 't')
            a->delay = atoi(optarg);
        else
            usage();
    }
    if (check_values(a) == FALSE)
        return (FALSE);
    return (TRUE);
}

しかし、-nオプションとして、次のようなチーム名を取得する必要があります。

./server -n team1 team2 team2

このまましか変えられない。

明らかに私はできる:

./server -n "team1 team2 team3"

チームを解析しますが、これは私の会社のためであり、チーム名を引用符で囲みたくありません。理由は聞かないでください...

シェルで引用符を使用せずにすべてのチーム名を取得するにはどうすればよいですか?

4

3 に答える 3

2

も使用できますoptindoptint遭遇したオプションの数を追跡します。 で検出された次のインデックスをoptind指しますargv[]getopt()

したがってargv、チームがあるかどうかを調べることができます。ただし、これを機能させるには、次のフラグメントのように optstring の「:」を省略する"p:x:y:nc:t:"か、ループで使用する前に optint の値をデクリメントする必要があります。

これは、ループを継続する必要があるかどうかを判断する単純な関数です。

int 
is_team ( const char* team ) {
    if ( team == NULL)
        return 0;
    else if ( team[0] == '-' ) /*new argument*/
        return 0;
    else
        return 1;
}

これは、「n」オプションに遭遇したときに行うことです。optstring でコロンを使用することもできますが、遭遇オプションもカウントされ、i = optind - 1機能する可能性があります。

case 'n':
    { /*note this scope is significant*/
        int i;
        for ( i = optind ; is_team(argv[i]); ++i  ) {
            printf ( "team = %s\n", argv[i]);
            //argument = ++*optarg;
        }
    }
    break;

これが役立つことを願っています。

于 2013-07-02T15:14:29.697 に答える