Getopt getting other options as argument

Asked

Viewed 26 times

0

I am making a code that should receive two strings for the execution with the parameters -i and -o, both of which can be null or not,the problem is found when the value of -i is not informed, it takes -o as argument.

while ((option = getopt (argc, argv, "i:o:")) != -1)
switch (option)
  {
  case 'i':      
    value_i = optarg;
    break;
  case 'o':      
    value_o = optarg;
    break;
 default:
    fprintf (stderr, "Usage: %s -i value -o value\n", argv[0]);
exit (1) ;
  }
printf ("value_i =  %s, value_o = %s \n", value_i, value_o);

The expected result of . /read -i -o hello would be that i = NULL and o = hello, but results in i = it and o = NULL

1 answer

0

According to the documentation here you need to put "::" after specifying the argument to make it optional.

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main(int argc, char ** argv)
{
  int option;
  char* value_i = "-1";
  char* value_o = "-1";

  while ((option = getopt(argc, argv, "i::o:")) != -1) // <---------
    switch (option)
    {
      case 'i':
        value_i = optarg;
        break;
      case 'o':
        value_o = optarg;
        break;
      default:
        fprintf (stderr, "Usage: %s -i value -o value\n", argv[0]);
        exit(1);
    }

  printf ("value_i = %s, value_o = %s \n", value_i, value_o);
}

Testing:

[~]
$./381305 -i -o hello
value_i = (null), value_o = hello 

[~]
$

Browser other questions tagged

You are not signed in. Login or sign up in order to post.