1

for example,

I have the structure options as following:

struct option options[] = {
    {"input", required_argument, NULL, OPT_INPUT},
    {"flag", no_argument, NULL, OPT_FLAG},

}

Now,if a user of the program by mistake omits the input file-name after -input command, passes the flag, like this:

./program -input -flag

The getopt_long_only treats "-flag" as the argument for input, thus taking it as the input file in the program, and not the next argument (and hence returning error for no argument being passed after -input). How can this be avoided?

I am using GUN/LINUX (2.6.34.3) and gcc (GCC) 4.4.2 20091027 (Red Hat 4.4.2-7).

Lavya
  • 1,475
  • 2
  • 17
  • 21
  • You don't mention your OS. If you can use GNU extensions (Linux, Unix), use getopt and refer to [this SO question](http://stackoverflow.com/questions/19604413/getopt-optional-arguments). – gnometorule Jun 03 '14 at 14:03

1 Answers1

0

I think the easiest way would be to simply check that the argument passed for -input isn't equal to -flag after you've read everything in. For example, if you were to store the required argument of input in char *temp, simply check that strcmp(temp, "-flag") is non-zero. If it is zero (i.e., they typed in ./program -input -flag), then print an error message and quit.

wolfPack88
  • 4,163
  • 4
  • 32
  • 47
  • yes, thats the only solution I can think of at the moment as well. The "problem" though, is that the options structure has around 40 members - so it'd mean checking 40 strings for all of the 40 cases, which sounds a bit tardy. I was wondering if there is any other way since this should not be a very rare problem. – Lavya Jun 03 '14 at 14:23
  • Maybe just check if the first character of the argument is `-`? – twalberg Jun 03 '14 at 15:57