我如何使用 getOpt 来确定 C 中是否没有给出任何选项?

How can I use getOpt to determine if no options are given in C?

我正在开发一个简单的程序,该程序应该根据参数将字符串更改为全部大写或全部小写。例如,如果可执行文件的名称是 change :

./change -u thiswillbeuppercase

THISWILLBEUPPERCASE

./change -l THISWILLBELOWERCASE

thiswillbelowercase

我遇到的问题是,如果没有提供任何选项,我无法弄清楚默认情况下如何执行大写操作。例如,这是我希望它执行的方式:

./change thiswillbeuppercase

THISWILLBEUPPERCASE

这是我的主要功能目前的样子:

int main(int argc, char *argv[]) {
int c;
while((c = getopt(argc,argv,"u:s:l:")) != -1){
    char *str = optarg;
    if(c == '?'){
        c = optopt;
        printf("Illegal option %c\n",c);
    } else{
    
        switch(c){
            case 'u':
                strupper(str);
                break;
            case 'l':
                strlower(str);
                break;
            case 's':
                strswitch(str);
                break;
            default:
                strupper(str);
                break;
    
        }
    }

}
return 0;

}

我尝试在 switch 语句的默认部分调用 strupper 函数,但这似乎不起作用。截至目前,该程序在没有提供任何选项时什么都不做。

我在 Whosebug 上搜索了类似的问题,我找到了 same issue 的人,但他们的问题与 bash 有关,而不是 C.

如果有人有任何建议,我将不胜感激。谢谢。

我会这样修改你的代码:

... several includes here...
int main(int argc, char *argv[]) {
    int c;
    while((c = getopt(argc,argv,"u:s:l:")) != -1){
    // ... no changes here ...   
    }
    if ( ( argc > 1 ) && ( c == (-1) ) ) { 
        // implement your default action here. Example
        // for ( int i = 1 ; i < argc ; i++ ) {
        //    strupper ( argv[i] ) ;
        // }
    } 
    return 0;
}