Search code examples
ccommand-line-argumentsargvargc

Argument type differentiate in C program


I have a main function,

int main (int argc, char **argv)
{}

I'm supposed to pass two different command-line arguments:

argv[1]=IP ADDRESS type
argv[2]=INTEGER type

For example, ./a.out IP-ADDRESS INTEGER. I am calling this binary with some other script.

The problem is while argv[1] is not available it behaves like INTEGER value as argv[1].

How can I put a check in that if argv is type INT don't make it to the argv[1] or only IP-ADDRESS type is allow in argv[1]?


Solution

  • int main (int argc, char **argv)
    

    is more commonly expressed as:

    int main (int argc, char *argv[])
    

    that is, argv is a pointer to an array of chars. What those chars represent is up to you, but generally these are going to be zero-delimited strings when the program is called on the command-line.

    If the user does not supply positional parameters then maybe you should be using options. See getopt().

    For example:

    #include <stdio.h>
    #include <unistd.h>
    #include <stdlib.h>
    
    /* Options:
           -i : integer argument
           -p : ip address
    */
    int main (int argc, char *argv[])
    {
        int option;
        int integer = 0;
        char *ip_address = NULL;
    
        opterr = 0;
        while ( (option=getopt(argc, argv, "i:p:")) != EOF ) {
          switch ( option ) {
            case 'i': integer = atoi(optarg);
                      break;
            case 'p': ip_address = optarg;
                      break;
            case '?': fprintf(stderr,"Unknown option %c\n", optopt);
                      exit(1);
                      break;
          }
        }
    
        if (integer)    printf("INTEGER: %d\n", integer);
        if (ip_address) printf("IPADDRESS: %s\n", ip_address);
    
        return 0;
    }
    

    Sample runs:

    ./a.out -i 1234 -p 128.0.0.1
    INTEGER: 1234
    IPADDRESS: 128.0.0.1
    
    ./a.out -i 1234 
    INTEGER: 1234
    
    ./a.out -p 128.0.0.1
    IPADDRESS: 128.0.0.1
    
    ./a.out -p 128.0.0.1 -i 1234 
    INTEGER: 1234
    IPADDRESS: 128.0.0.1
    
    ./a.out -x stuff 
    Unknown option x