Saurabh Rana
Saurabh Rana

Reputation: 3548

Define custom command-line parameters in C?

I need to pass a 'key' as a parameter from terminal. It should run as
./a.out -k100101001
where 10011001 is the key and -k is the flag to specify it.
If I need to pass a filename along with the key it should run as
./a.out -k10011001 -iparameter.txt
where parameter.txt is the filename and -i is the flag to specify that.

NOTE: I have several parameters to pass and parameter values are followed after the flag without space(-iparameter.txt), plus I don't know the order of the flags so doing something like this won't help.

int main(int argc, char **argv) {
if (argc == 2) {
    if (!strcmp(argv[1], "-k")) something();
    if (!strcmp(argv[1], "-i")) something();
}

Any suggestion for C? I'm using Ubuntu to run my program. Thanks.

Upvotes: 0

Views: 619

Answers (1)

Joël Hecht
Joël Hecht

Reputation: 1842

Using a loop through argv should do it.

int main(int argc, char *argv[])
{
    int numArg;

    for (numArg = 1; numArg < argc; numArg++)
    {
        if (argv[numArg][0] == '-')
        {
            switch (argv[numArg][1])
            {
            case 'k' : somethingAboutKey(argv[numArg] + 2); // The parameter's value is passed directly to the function
                       break;
            case 'i' : somethingAboutFile(argv[numArg] + 2);
                       break;
            }
        }
    }
}

Upvotes: 2

Related Questions