Search code examples
cgetopt-long

How to restrict "--" using getopt in linux c?


I have to restrict when the user gives "--" as an option. For example:

./test --

should thrown an error. For the sake of parsing I am using getopt

How to achieve this using getopt?


Solution

  • getopt is intended for implementing programs which conform to the POSIX Utility Syntax Guidelines where -- has a special meaning of causing all subsequent arguments to be treated as non-options even if they have the form of options (e.g. rm -- -f to remove a file named -f). There's no explicit way to suppress this behavior. You could try checking whether argv[optind-1] is "--" after getopt finishes, but this would give false positives in cases where the "--" was the argument to an option that takes an argument (something like -f -- where -f needs an argument) which you might need to work around.

    If you really want argument handling that does not conform to the Utility Syntax Guidelines you might be better off rolling your own from scratch.