Command Line Options

How do you retrieve command line switches for your program?

--------------------------------------------
I will bend your mind with my spoon...

Comments

  • if you have a main function the parameter switches are passed with an array:

    [code][blue]int[/blue] main([blue]int[/blue] argc, [blue]char[/blue] *argv[], [blue]char[/blue] *envp[])[/code]

    argc is the number of arguments, argv[0 .. argc - 1] contains pointers to the strings.

    the WinMain function receives the commandline switches in a single string (3rd parameter).

    : How do you retrieve command line switches for your program?
    : --------------------------------------------
    : I will bend your mind with my spoon...
    :

  • : How do you retrieve command line switches for your program?
    : --------------------------------------------
    : I will bend your mind with my spoon...
    :

    Here's a small (and simple) example:
    [code]
    int capitalize_switch(char *param)
    // returns != 0 if the param is one of "/c" or "/C"
    {
    return param[0] == '/' && 'C' == toupper(param[1]);
    }

    int main(int argc, char *argv[])
    {
    // do we have at least one parameter ?
    if (argc > 1) {
    // maybe more ?
    if (argc > 2) {
    // if we recognize the switch, perform an action ...
    if (capitalize_switch(argv[2]))
    argv[1][0] = toupper(argv[1][0]);
    // ignore the other (possible) parameters
    }
    // output the first parameter (the required one)
    puts(argv[1]);
    } else {
    // no parameters - display usage
    fprintf(stderr, "Usage:
    %s [/C]
    ", argv[0]);
    return -1;
    }

    return 0;
    }
    [/code]

    Cheers,
    Blitz.
  • Hey !

    You can use this syntax :

    [red] main(int argc,char **argv,char **env)[/red]

    the [red]argc[/red] refers to the number of parameters and the
    [red]argv[/red] string array is the list of parameters .For
    example if the program syntax is :

    [blue] this thing sucks[/blue]

    then

    [red]
    argc=4
    argv[0]=
    argv[1]=this
    argv[2]=thing
    argv[3]=sucks
    [/red]

    You may also use the [red]atoi()[/red] function to process numbers as arguments .So that is how command line parameters
    are processed .Switches may involve using flags in your programs ,as the switches are themselves only strings .

    Bye



    Karthik Kumar V

Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories