Sunday, February 5, 2012

How do you access command-line arguments ?

A Program is started by the operating system calling a program's main() function .
main() function is the only function in C that can be defined in multiple ways. It can take no arguments , two arguments or three arguments 

The two and three argument forms allow it to receive arguments from the shell ( command-line). The two argument form takes an int and an array of strings. When defining main() function arguments any name can be given but it is convention to call them argc and argv[].

The first argument (argc) holds a count of how many elements there are in the array of strings passed as the second argument(argv). The array is always null terminated so argv[argc]=NULL.

e.g :
int main( int argc, char *argv[])
         int i;
         printf("argv[%d] == %d\n",i,argv[i]);
         return 0;

The integer,argc, is the argument count(hence argc). It is the number of arguments passed into the program from the command line, including the name of the program.
The array of character pointers is the listing of all the arguments. argv[0] is the name of the program. After that , every element number less than argc is command line arguments. You can use each argv element just like a string , or use argv as a two dimensional aray.


No comments:

Post a Comment