[OCLUG-devel] C argum

Scott Edwards msedwardsus at yahoo.com
Sat Apr 26 13:53:24 PDT 2014


Hi Joshua,

>________________________________
> From: Joshua Robinson <shooki.robinson at gmail.com>
>To: oclug-devel at www.oclug.org 
>Sent: Saturday, April 26, 2014 12:04 PM
>Subject: [OCLUG-devel] C argum
> 
>Greetings OcLugers,
>
>
>In C need to pass on the command line: 
>
>MyProjName  -s user at host and -u user_name 
>
>
>How do I do that (many year since I did C), little code would be nice ? 
>
>
>Cheers,
>Joshua Robinson




To support arguments from the command line, you need to implement the "main" function so that it receives the argument count (argc) and the argument vector (argv), like this:


----------------------------------------

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

}

----------------------------------------


"argc" will contain the number of arguments entered on the command line, including the name of the executable file.


"argv" is an array of null-terminated strings, which are the commands fetched from the command line, including the name of the executable file. This array is terminated with a NULL pointer.

So if you were to run your program in this manner:

   ./a.out  one two three

The "argc" parameter would have a value of four, and the argument vector would look like this:

   argv[0] = "./a.out"
   argv[1] = "one"
   argv[2] = "two"
   argv[3] = "three"
   argv[4] = NULL


To illustrate, here's a quick "main" function that simply displays the arguments passed to it:

----------------------------------------

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

    // loop while argv elements are non-NULL
    while (argv[index])
        {
        puts(argv[index]);
        ++index;
        }

    return 0;
}

----------------------------------------


Hope this helps,

-- Scott Edwards



More information about the OCLUG-devel mailing list