What exactly does the getopt () function do? from the library unistd.h? [closed]

-1

What exactly does this function do? and how could I apply it to my code?

    
asked by thc 04.02.2018 в 22:38
source

1 answer

1

getopt is a function that facilitates the interpretation of the application's start parameters.

There are many programs that do not have a graphical interface and the configuration is provided through a command line:

ls -l -a

In the previous example, l is a configuration parameter. This parameter could easily be read using getopt :

char c;
while ((c = getopt (argc, argv, "la:")) != -1)
{
  switch (c)
  {
    case 'a':
      // Parametro "a" presente
      // ...
      break;
    case 'l':
      // Parametro "l" presente
      // ...
      break;
  }
}

Or you could program it by hand (taking into account that the parameters can be disordered:

for( int i=1; i<argv; i++ )
{
  if( strcmp(argc[i], "-a") == 0 )
  {
    // Parametro "a" presente
    // ... 
  }
  if( strcmp(argc[i], "-l") == 0 )
  {
    // Parametro "l" presente
    // ...
  }
}

Notice that in this second case the if are practically the same, which can lead to errors that are difficult to detect.

getopt has an extensive configuration to adapt to the different types of tickets that may be needed.

    
answered by 05.02.2018 в 08:05