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.
The getopt() function is a builtin function in C and is used to parse command line arguments. Syntax: getopt(int argc, char *const argv[], const char *optstring) optstring is simply a list of characters, each representing a single character option.
To be clear, getopt is not part of the C standard, it is part of the POSIX standard. A lot of things that we take for granted in C come from POSIX rather than the C standard itself. I think you will run into many different approaches for handling argument parsing.
Getopt is a C library function used to parse command-line options of the Unix/POSIX style. It is a part of the POSIX specification, and is universal to Unix-like systems. It is also the name of a Unix program for parsing command line arguments in shell scripts.
RETURN VALUE The getopt() function returns the next option character specified on the command line. A colon (:) is returned if getopt() detects a missing argument and the first character of optstring was a colon (:).
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With