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

标签 c command-line arguments command-line-arguments getopt

我正在开发一个简单的程序,该程序应该根据参数将字符串更改为全部大写或全部小写。例如,如果可执行文件的名称是 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 函数,但这似乎不起作用。截至目前,该程序在未提供任何选项时不执行任何操作。

我在 stackoverflow 上搜索类似的问题,然后我发现有人使用 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;
}

关于c - 我如何使用 getOpt 来确定 C 中是否没有给出任何选项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35421591/

相关文章:

c - 在 C 中声明一个与数组一起使用的结构

visual-studio-2008 - 如何从命令行从Visual Studio解决方案获取最新信息?

bash - 为文件夹中的多个文件重命名并删除 _ 之前的每个字符

c - 使用 execve 时传递整数参数

python - 将全局值作为参数传递给装饰器和函数

c# - 在 C# 中计算 CRC16

c - 同一互斥锁的多个锁上的线程行为

c++ - 从C可执行文件加载C++动态库时收到错误 “undefined symbol”

java - 找不到/安装 libXtst.so.6?

function - 以下涉及 Go 中 channel 的函数参数有什么区别?