简体   繁体   中英

getopt_long_only: how to prevent the next option as being taken as argument for the previous option with “required_argument” flag

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).

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 (ie, they typed in ./program -input -flag ), then print an error message and quit.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM