Proper Use of getopt

Here is an example of using GNU getopt . I understand most parts of the code, but I have a few questions:

  • Why is ctype lib enabled?

    I want to say that unistd.h needed for getopt , stdlib.h needed for abort , and stdio.h is the standard lib for io .

  • In the default case, why do we use interrupt? cant 'we just use return 1 ;?

  • I would like someone to share a link with more details on optopt , optind and optarg , if possible.

+4
source share
1 answer

In short:

optopt , optind and optarg are external characters. They are global and declared in unistd.h .

optopt ( opt = option ) is usually not required. It should be the same as the value returned by the getopt call.

optarg ( arg = argument ) is easy. This is for the argument for the flag. for example, if -f is a parameter that requires a file name argument ( optstring contains f: , you can do something like

  case 'f': filename = optarg; break; 

optind ( ind stands for index ) tells you where the selection process ended after the end of your while (flag = getopt...) block while (flag = getopt...) .

eg. before adding parameter handling, your script might look like this:

 // print command line arguments, start at 1 to skip the program name for (int i = 1; i < argc; i++) { printf("arg[%d]=%s\n", i, argv[i]); } 

after adding the getopt block to process the parameters, you can do

 // print command line arguments remaining after option processing for (int i = optind; i < argc; i++) { printf("arg[%d]=%s\n", i, argv[i]); } 

or

 // skip command line options argc -= optind; argv += optind; // print command line arguments for (int i = 0; i < argc; i++) { printf("arg[%d]=%s\n", i, argv[i]); } 

Unless you have the necessary command line arguments, you don't need to worry about optind .

+5
source

Source: https://habr.com/ru/post/1499977/


All Articles