February 07, 2010

using getopt : is it worth the effort ?

I was recently going through the GNU getopt library for parsing command line options. On a *nix system with online man pages installed, you should be able to read the manual pages for the getopt C library functions by doing something like
man 3 getopt
Now what I am left wondering about is, whether the complexity of using the library functions when the number of arguments your program requires is one or two, worth it ? Whenever I have had to implement similar functionality into my program all I have done is use a while loop over argv until I found all the required arguments. Something like this :
.
.
.
i = 0;
num_args_found = 0;
do{
 if (argv[i] == '-'){
           /*check for all valid options */
           /*if invalid character found then skip and continue */
 }
 i++;
 num_args_found++;
}while (i < argc);
if (num_args_found < requried_num_of_args){
 printf ("The requried arguments were not found\n");
 exit (0);
}
/*rest of the program here */.
.
.
though I am sure this is the best of the approaches, and even I have sometimes used a better one or a modified version of the above code, like to show exactly which arguments were missing. But the point of discussion here is that, when the expected number of arguments is less than three or four, the complexity of using a library function is much more than that for writing some custom code as above.

No comments:

Post a Comment