4

So far I've been using getopt_long to parse options for a command line C program.

Is there a way to stop getopt_long parsing when it hits a non-option argument? If not, what's the best way to handle this in C?

To give an example, I'd like to handle commands in a similar way to git, and have general arguments before a command, and command-specific arguments after it:

git [general options] <command> [command options]

e.g.:

git --bare commit -a
git -p --bare status -s

-p and --bare are general options, and can be used with all commands, whereas -a is specific to the commit command, and -s specific to the status command.

Using getopt_long will try and parse all the options first, and then leave the non-option arguments to be handled. I'd ideally like to stop parsing once I hit a non-option (i.e. the command), and then pass the remaining arguments to a command-specific option parser.

Dave Challis
  • 3,525
  • 2
  • 37
  • 65

1 Answers1

6

The GNU Getopt manual says:

POSIX demands the following behavior: The first non-option stops option processing. This mode is selected by either setting the environment variable POSIXLY_CORRECT or beginning the options argument string with a plus sign (‘+’).

hmakholm left over Monica
  • 23,074
  • 3
  • 51
  • 73
  • 1
    +1. It's funny how this appears in the Linux Programmer's Manual, i.e. the Linux manpages, but not in the "authorative" [Glibc manual](http://www.gnu.org/s/libc/manual/html_node/Getopt-Long-Options.html#Getopt-Long-Options). – Fred Foo Aug 15 '11 at 15:44
  • Thanks, that works perfectly. I'd been staring too long at getopt_long documentation and not enough at `man getopt`! – Dave Challis Aug 15 '11 at 15:44