0

How can I parse arguments without the hyphen in C?

I.e. virsh install vm

or

git pull origin master

When I tried it out, if there is no - prefix, everything just gets ignored and argc returns 1 (argv[0] is the program call).

I'm using Linux, but it would be nice if there was a cross platform method to achieve this.

UPDATE: the problem was me using a # in front of the first argument, I was trying to pass in #XX eg number_program #12. Needless to say this doesn't work.

Lundin
  • 195,001
  • 40
  • 254
  • 396
jayjay
  • 1,017
  • 1
  • 11
  • 23
  • It is very unclear what it is you are asking. ***[READ](http://stackoverflow.com/help/how-to-ask)*** this for help on asking a good question. – ryyker Oct 08 '13 at 14:45
  • Um, your `argc` and `argv` will reflect whatever is on the command line. – chrisaycock Oct 08 '13 at 14:45

2 Answers2

2

Are you using some library to parse the arguments for you? There is no special 'hyphen' arguments when passing in parameters to a C program specifically. Parse argv however you like.

For example:

#include <stdio.h>

int main(int argc, char **argv)
{
        int i;
        for(i=0; i<argc; i++) {
                //dont do this without proper input validation
                printf("%s\n", argv[i]);
        }

        return 0;
}

Example run:

$ ./a.out test test test -hyphen
./a.out
test
test
test
-hyphen
mikew
  • 912
  • 2
  • 11
  • 22
1

argv contains the program name and the arguments to the program, in the order they were given in the command line.* Hyphens aren't special; they just make it easy for both people and computers to separate options from other args.

If you want to interpret args a certain way, that's your prerogative. That's what git does, basically interpreting argv[1] (if it exists, of course) as the name of a subcommand. And you don't need any libraries in order to do that. You just need to decide how you want the args interpreted.

* Modulo some cross-platform differences in how args are parsed; *nix typically does some pre-parsing for you and expands wildcard patterns, for example. You won't have 100% cross-platform compatibility unless you understand those differences and are ready for them.

cHao
  • 84,970
  • 20
  • 145
  • 172