Accessing command line parameters/arguments

来源:互联网 发布:天庭淘宝店 无常著txt 编辑:程序博客网 时间:2024/05/29 13:57
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[])
{
  /*
   * Look for -a or -d in command line
   */
  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);
}


/*
 * Program output when run as
  myprog.exe -a -b -d name
  
  Found -a
  Unknown switch -b
  Found -d
  Found name
*/




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);
}


/*
 * When invoked with:
 E:\>a.exe -parm1 -a
 * The output is:
  argv[0] is E:\a.exe
  argv[0][0] is E
  argv[0][1] is :
  argv[0][2] is \
  argv[0][3] is a
  argv[0][4] is .
  argv[0][5] is e
  argv[0][6] is x
  argv[0][7] is e
  argv[1] is -parm1
  argv[1][0] is -
  argv[1][1] is p
  argv[1][2] is a
  argv[1][3] is r
  argv[1][4] is m
  argv[1][5] is 1
  argv[2] is -a
  argv[2][0] is -
  argv[2][1] is a
 *

 */


From: www.Cprogramming.com