13

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.

Pupi
  • 131
  • 1
  • 1
  • 5
  • possible duplicate of [Using getopt in C with non-option arguments](http://stackoverflow.com/questions/18079340/using-getopt-in-c-with-non-option-arguments) – Peter M Nov 17 '14 at 15:57

1 Answers1

18

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;
}
Patrick
  • 555
  • 1
  • 6
  • 25
Klas Lindbäck
  • 33,105
  • 5
  • 57
  • 82
  • 3
    Don't use atol(). It has no error recovery and hasn't been suitable for new code for a long time. Use strtol() instead. – SO Stinks Apr 16 '20 at 02:06
  • Don't use strtol, as it throws an exception which if not handled can ruin your code. Additionally exception safe programming ruins the structure of your code and turns the system into an absolutely horrendous mess. – Owl Jan 25 '22 at 12:08
  • @Owl: functions in C do not throw exceptions; there are no exceptions in C. – Jonathan Leffler Dec 22 '22 at 20:32
  • Error messages should be printed on `stderr`, not `stdout`. – Jonathan Leffler Dec 22 '22 at 20:33