facebook like button

06 June, 2011

Command line arguments

What is "command line argument"??
You have seen that any built-in or user defined function can take some arguments when it is called. main() can also take arguments without exception because it is a built-in function. Every function takes arguments when it is called (or before it starts running). You people also know that main() is the start point of the program. So by guessing you can say that main() should take argument even before the program starts to execute. Your thinking is correct. If you are using unix, ubuntu or any other compiler in which you have to write a command to compile and run your code, you can give arguments to main() while giving command to run the program. Ex. in unix based OS when you give ./a.out command after that arguments to main() can be given. These arguments are given in the command this is why these are called command line arguments. For all this the programmer also need to specify in the program that main() has to take arguments or not.
   main() can be declared to take 2 arguments first is an integer type and second is a array of character pointers. Usually first argument is named 'argc' abbreviation to 'argument counter' because this automatically inherits the value of number of arguments given. The second argument is usually written agrv probably abbreviation of 'argument variable' because this is the variable which takes the array of strings given as arguments after the file name (file name inclusive). After you give arguments to main(), these (argc and argv) can be used as normal variables in main() in the same way we gave arguments to other functions and used inside them.

In program code:
int main(argc, *argv[])
{
//program body
}


In ubuntu or or any other unix based system --
command to compile is same which is:
cc file1.c
After this a file named a.out is created in the same directory. To run that a.out file we used to write ./a.out now we'll write like this:
./a.out bla bla bla
where "bla bla bla" are command line arguments.

No comments:

Post a Comment

feel free to ask your doubts... if any
you can post your doubts on
www.facebook.com/programsimply