玩转 getopt

Playing around with getopt

您好,我对编码很陌生,并试图找出此 getopt 不起作用的原因。我的编译器抱怨 "i:o:"

错误 C2664 'int getopt(int,char **,char *)': 无法将参数 3 从 'const char [5]' 转换为 'char *'

int main(int argc, char *argv[])
{
    int opt;
    while ((opt = getopt(argc, argv, "i:o:")) != -1)
    {
        switch (opt)
        {
        case 'i':
            printf("Input file: \"%s\"\n", optarg);
            break;
        case 'o':
            printf("Output file: \"%s\"\n", optarg);
            break;
        }
    }
    return 0;
}    

这很奇怪,因为当我阅读有关 getopt 的内容时,我看到了这个 "The options argument is a string that specifies the option characters that are valid for this program."

只需使用字符串指针:

char* opts = "i:o:";
getopt(argc, argv, opts);

根据您的错误消息,getopt 函数需要一个 可写 选项字符串。你可以通过制作一个 non-const 字符数组来做到这一点:

int main(int argc, char *argv[])
{
    // non-const char array
    char opts[] = "i:o:"; // copy a string literal in

    int opt;
    while ((opt = getopt(argc, argv, opts)) != -1)
    {
        switch (opt)
        {
        case 'i':
            printf("Input file: \"%s\"\n", optarg);
            break;
        case 'o':
            printf("Output file: \"%s\"\n", optarg);
            break;
        }
    }
    return 0;
}

你的原始代码在 LinuxGCC v7 上对我来说工作正常。您使用的版本的函数签名似乎不同。

我的系统上是:

int getopt (int argc, char** argv, const char* options);

但在您的系统上它似乎是:

int getopt(int,char **,char *);

最后一个参数缺少 const 导致错误,这就是为什么你需要给它一个 non-const 字符串。

注意: 我不建议为此使用 const_cast,因为有些人可能会受到诱惑。您永远不知道该功能是如何实现的,或者该内部实现是否会在某个时候发生变化。