tags:

views:

94

answers:

2

Here, i have a program, which takes arguments (how surprising...). I want him to have several arguments, as:

./myprogram -f filename.txt -x -o

so i want main args with "-", and these arg shall accept an other arg, in the example, a filename.

I have this structure, very simple:

int main(int argc, char *argv[])
{
    printf("Program name: %s\n", argv[0]);

    while ((argc > 1) && (argv[1][0] == '-'))
    {
        switch (argv[1][1])
        {
            case 'f':
                printf("%s\n",&argv[1][3]);
                break;

            case 'd':
                printf("%s\n",&argv[1][2]);
                printf("%s\n",&argv[1][2]);
                break;

            default:
                printf("Wrong Argument: %s\n", argv[1]);
                usage();
        }

        ++argv;
        --argc;
    }


    return 0;
}

As you can see, in case of -d, this prints what's following the argument, without space; here is a sample output:

./myprogram -dfilename
Program name: myprogram
filename
filename

and with the -f parameter,

./myprogram -f filename
Program name: myprogram
ffilename

it prints twice the first letter, and i don't understand why. Could someone help?

+2  A: 

Try using a standard argument library, such as GNU getopt.

The problem with your code is that -f should be printing argv[2][0], not argv[1][3]. It also needs to check that argc is > 2.

Borealid
`getopt` is actually a standard part of POSIX. If you want the extended GNU functionality (support for options after non-option arguments or long `--` options) then you should copy GNU `getopt.c` into your project and use it.Also, some people (myself included) find the `getopt` style API clumsy and inefficient. You might be better off making your own API which takes a structure describing which characters are valid, whether they take arguments or just act as flags, and where to store the results.
R..
+4  A: 

argv contains an array of strings. Argv[0] contains the program name, argv[1] contains -f in your case, argv[2] contains filename. If you print argv[1][3], you are printing the string starting at the third letter of -f. There is no such thing, so the behavior is undefined.

Sjoerd
Mhh... okay, but then should not i fix a certain order in arguments, e.g. force the user to use some arguments before others?
Araelle