0

作为一个例子,我想实现以下功能:listtool [-s | -a NUM] <字符串>

我的方法如下:

int opt;
int opt_s = -1, opt_a = -1, num;
char *optstr ="<not yet set>";
num = -1;

if( argc < 3 || argc > 4 ) {
    fprintf(stderr, "Wrong number of arguments");
    usage();
}

/* Options */
while ((opt = getopt(argc, argv, "sa:")) != -1) {
    switch (opt) {
    case 's': {
        if (opt_s != -1) {
            fprintf(stderr, "opt_s multiple times\n");
            usage();         /* does not return */
        }
        else if (opt_a != -1) {
            fprintf(stderr, "Please only choose one option\n");
            usage();
        }
        else {
            ++opt_s;
            break;
        }
    }
    case 'a': {
        if (opt_a != -1) {
            fprintf(stderr, "opt_a multiple times\n");
            usage();        /* does not return */
        }
        else if (opt_s != -1) {
            fprintf(stderr, "Please only choose one option\n");
            usage();
        }
            ++opt_a;
            ++num; 
            break;
        }
    case '?': {
        usage();
        break;
    }
    // Impossible
    default: {
        assert(0);
    }
    }
}

/* Arguments */
if( num > -1 ) {
    if( (argc - optind) != 2 ) {
        usage();
    }
    num = (int)strtol( argv[optind], NULL, 0 );
    *optstr = argv[optind+1];
}
else {
    if( (argc - optind) != 1 ) {
        usage();
    }
    *optstr = argv[optind];
}

这段代码有一些东西不起作用。我想知道为什么,以及这样做的正确方法是什么。

  • 首先 getopt 试图解析参数,然后进入 ? 案子
  • (optind - argc) 没有抛出正确数量的参数
  • 将 argv[optind] 分配给 optstr 会抛出:

    warning: assignment makes integer from pointer without a cast

预先感谢您的每一个答案

4

1 回答 1

1

第三题的答案the assignment of argv[optind] to optstr throws: warning ?如下,

char *optstr; 
*optstr = argv[optind]; // Wrong if LHS is a string rather a char


optstr = argv[optind]; // Correct one

这里,optstr是一个指向可以存储单个字符或字符串的字符的指针。也*optstrchar和 RHSargv[optind]是一个字符串指的是一个指针。因此发出警告。

于 2013-11-13T18:56:55.967 回答