Mandatory parameter getopt in C

18.4k views Asked by At

I have this piece of code in C

while((i = getopt(argc, argv, ":p:h:s:n:l:f:SLNF")) != -1)
    switch(i){
        case 'p': printf("Porta obbligatoria\n");
                  break;
        case 'h': printf("hostname\n");
                  break;
        case 's': printf("Surname\n");
                  break;
        case 'n': printf("Name\n");
                  break;
        case 'l': printf("Login\n");
                  break;
        case 'f': printf("Faculty\n");
                  break;
        case 'S': printf("Print Surname\n");
                  break;
        case 'L': printf("Print Login\n");
                  break;
        case 'N': printf("Print First name\n");
                  break;
        case 'F': printf("Print Faculty\n");
                  break;
        case '?': printf("USAGE\n");
                  break;
        default: printf("USAGE default\n");
                  break;


    }


   return 0;
}

How can I have only one mandatory parameter? In my case is p.

For example:

./MyProgram -p 80 -h 127.0.0.1

Result ok.

./MyProgram -h 127.0.0.1

Error because missing -p

Only -p.

Thanks in advance.

1

There are 1 answers

4
Klas Lindbäck On BEST ANSWER

Usually you use the while loop to store the values and then check the mandatory options after the loop:

    int p = -1;

    while((i = getopt(argc, argv, ":p:h:s:n:l:f:SLNF")) != -1)
        switch(i){
            case 'p': p = (int)atol(optarg);
                      break;
            <skipped a few options >
            default: printf("USAGE default\n");
                      break;
        }

    // Check mandatory parameters:
    if (p == -1) {
       printf("-p is mandatory!\n");
       exit 1;
    }

    return 0;
}