e.g. Something like 'ls' .. it takes a lot of switches -l, -t, -r etc. Off course this parsing can be done manually but you will have to invest more than needed time if you want to build a robust parser. So, using getopt() is the better choice.
Function -
int getopt(int argc, char * const argv[],const char *optstring);
takes argument count and argument array passed to main and in addition takes list of switches that you
want to recognize. By default, it considers that your option will be appended by a hyphen sign (e.g. -l, -p etc).
- You can iterate through the command line options by calling getopt() repeatedly.
- If any switch has argument, it is succeeded by a colon (:) in optstring (e.g. getopt(argc,argv,"p:"))
- If any switch has optional argument, it is succeeded by double colon (::) (e.g. getopt(argc,argv,"p::"))
- If any switch has optional argument, it is pointed to by external variable named 'optarg' when that switch is read.
- If getopt() does not recognize an option character, it prints an error message to stderr, stores the character in optopt, and returns ’?’
- Returns -1, when it runs out of switches on command line.
Example:
while ( -1 != (option=getopt(argc,argv,"afs:n:i:p:r:t") ) )
{
switch(option)
{
case 'a':
// Take action for 'a'
break;
case 'f':
// Take action for 'f'
break;
case 's':
// Take action for 's'
strcpy(var,optarg); // argument for switch '-s' is available in 'optarg'
break;
case 'n':
// Take action for 'n'
char_ptr = atoi(optarg);
break;
case 'i':
// Take action for 'i'
strcpy(var,optarg);
break;
case 'p':
// Take action for 'p'
strcpy(var,optarg);
break;
case 'r':
// Take action for 'r'
strcpy(filename,optarg);
break;
case 't':
// Take action for 't'
break;
case '?':
command_usage();
exit(1);
break;
default:
command_usage();
exit(1);
}
}
--------------------------------------------
getopt() manual can better explain this but this is quick hello world to get you started.