ccommand-lineargumentscommand-line-argumentsgetopt

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


I'm working on a simple program that supposed to change a string to all uppercase or all lowercase depending on the arguments. For example, if the executable's name is change :

./change -u thiswillbeuppercase

THISWILLBEUPPERCASE

./change -l THISWILLBELOWERCASE

thiswillbelowercase

The issue im having if that i cannot figure out how to perform the uppercase action by default, if no options are provided. For example, this is how i would like it to perform:

./change thiswillbeuppercase

THISWILLBEUPPERCASE

Here is what my main function looks like currently:

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;

}

I tried calling the strupper function in the default part of the switch statement but that doesn't seem to work. As of now the program does nothing when provided with no options.

I search stackoverflow for similar questions and i found someone with the same issue, but their question is related to bash and not C.

If anyone has any advice i would really appreciate it. Thank you.


Solution

  • I would change your code this way:

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