Playing around with getopt

Playing around with getopt

本文关键字:getopt with around Playing      更新时间:2023-10-16

嗨,我对编码很陌生,并试图找到为什么这个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的信息时,我看到了这个"选项参数是一个字符串,指定对此程序有效的选项字符。

根据您的错误消息,getopt函数需要一个可写的选项字符串。你可以通过创建一个非常量字符数组来做到这一点,如下所示:

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;
}

您的原始代码在与GCC v7 Linux上对我来说效果很好.您正在使用的版本的功能签名似乎不同。

在我的系统上是:

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

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

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

最后一个参数缺乏const会导致错误,这就是为什么您需要给它一个非常量字符串的原因。

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

只需使用字符串指针:

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