This item was added on: 2003/02/24
When you start a program from the command line, it is sometimes necessary to use parameters along with the program name. For example:
copy source.txt target.txt
This is known as using command line arguments or parameters. To access them within your program, you need to declare the main()
function correctly:
int main (int argc, char *argv[])
Read here for a more detailed explanation of the main() definition.
If the value of argc is greater than 0, the array members argv[0] through argv[argc-1] inclusive shall contain pointers to strings, which will be the command line arguments. argv[0] will contain the program name, argv[1] the first command line arg, argv[1] the second and so on. Finally, argv[argc] is guaranteed to the a NULL pointer, which can be useful when looping through the array.
Here are some snippets of code showing ways to access the command line arguments.
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[])
{
int i;
for (i = 1; i < argc; i++)
{
if (argv[i][0] == '-')
if (argv[i][1] == 'a')
puts ("Found -a");
else if (argv[i][1] == 'd')
puts ("Found -d");
else printf ("Unknown switch %s\n", argv[i]);
else if (strcmp(argv[i], "name") == 0)
puts ("Found name");
}
return(0);
}
And some more:
#include <stdio.h>
int main(int argc, char *argv[])
{
if (argc > 0)
printf ("Program name is >%s<\n", argv[0]);
return 0;
}
#include <stdio.h>
int main(int argc, char *argv[])
{
int i;
for (i = 1; i < argc; i++)
puts(argv[i]);
return 0;
}
#include <stdio.h>
int main(int argc, char *argv[])
{
while (--argc)
printf ("%s ", *++argv);
return 0;
}
This next program prints the command line details in a manner which should help you understand how the arrays are accessed in memory.
#include <stdio.h>
int main(int argc, char *argv[])
{
int i, j;
for (i = 0; i < argc; i++)
{
printf ("argv[%d] is %s\n", i, argv[i]);
for (j = 0; argv[i][j]; j++)
printf ("argv[%d][%d] is %c\n", i, j, argv[i][j]);
}
return(0);
}