Sunday 18 December 2011

Learn to use the command line parameters

You may have often seen programs that take command line arguments. If you have ever wondered about how to write a program that would utilize these arguments then this is the post for you. Command line arguments are passed as strings to your program even if the argument is a number. Suppose your program takes unknown numbers as CL arguments and you need to add them and print the result. How would you do it. Below is the complete program that demonstrates this:

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
    int i, sum = 0;
    for(i = 1; i < argc; i++)         //Loop through argv[] to find the sum of arguments
    {
        sum += atoi(argv[i]);        //convert argument argv[i] to integer and add to previous sum
    }

    printf("Sum is %d\n", sum);
    return 0;
}

The command line information is passed to our program in two variables: argc and argv. argc contains the number of arguments passed. argv[] contains the arguments in the form of strings. Thus, argv[0] is the first argument, argv[1] second and so on. However, remember that even if no arguments are passed, argc is always 1. This is because the program name itself is always passed to the program by the operating system. This argument is stored in argv[0] always. Thus, the arguments that we actually want here start from argv[1]. Now if we analyze the code in the light of this information, we should be able to understand it. Please feel free to ask or give suggestions if anything is not clear.

No comments:

Post a Comment