Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C (http://www.go4expert.com/articles/c-tutorials/)
-   -   Command Line Argument (http://www.go4expert.com/articles/command-line-argument-t21746/)

techgeek.in 13Apr2010 23:46

Command Line Argument
 

Introduction



A command line argument is a parameter which is passed to a program at the time or instant when it is invoked or executed from the command line .This is accomplished by passing information to main() method of the program. It is the information that directly follows the program’s name on the command line when you run it This parameter may represent any information for example a filename the program should process. This eliminates the need for the program to request the user to enter the information during program execution. An application can accept any number of arguments from the command line. The space character usually separates the command line arguments.

Programming languages such as C,C++ and java allow a program to interpret the command line arguments by handling them as string parameters in the main function.

Implementing Command Line Argument in C



Every C program has one main function which marks the start of the program. This main function has a prototype which can take two arguments called argc and argv as follows:

main(int argc, char *argv[])
{


}

When the main is called by the system at the time of execution the information contained in the command line is passed on to the program through these arguments.

The variable argc is an argument counter that counts the number of arguments on the command line.

The argv is an argument vector that represents an array of character pointers that point to the command line arguments. The size of this array is equal to the value of argc.The first parameter in the command line that is argv[0] always represents the program name.

Eg. Let us assume that there is a program which copies the contents of a file named X_FILE to another file named Y_FILE. The filename where the executable code is stored is PROGRAM.

So we can pass the source and destination file name through command line as

C>PROGRAM X_FILE Y_FILE
Here
argc=3
argv[0]=PROGRAM
argv[1]= X_FILE
argv[2]= Y_FILE

Sample Program

Program statement: A program that will receive a filename and a line of text as command line arguments and write the text to the file.

File_write program ( program which gives the file name and the line to be written to that file from outside)

Code:

#include <stdio.h>
void main(int argc, char *argv[])
{
        FILE *fp;
        int i;
        char word[20];
        fp=fopen(argv[1], “w”);  /* open file with name argv[1]  */
        printf(“\n No. of  arguments in command line = %d\n”,argc);
        for(i=2;i<argc;i++)
                fprintf(fp,”%s”,argv[i]); /* write to file argv[1]  */
        fclose(fp);

        /* writing the contents of the file to the screen  */

        printf(“Contents of %s file\n\n”, argv[1]);
        fp=fopen(argv[1],”r”);
        for(i=2;i<argc;i++)
        {
                fscanf(fp,”%s”,word);
                printf(“%s “,word);
        }
        fclose(fp);
}

OUTPUT

C:\>File_write TEXT.txt I AM A GOOD PERSON

No. of arguments in command line = 7

Contents of TEXT.txt file

I AM A GOOD PERSON

(In the above example we assume that the file TEXT.txt is located in the C drive. If not, exact path is to be given in the argument.)

Implementing Command Line Argument in C++



The concept of command line arguments in C++ is exactly the same as C. The prototype of main() function is also the same. Only the syntax differs.

Example: Display all command-line arguments

Code:

#include <iostream.h>
    int main(int argc, char **argv)
          {
                cout << "Received " << argc << " arguments...\n";
                for (int i=0; i<argc; i++)
                  cout << "argument " << i << ": " << argv[i] << endl;
                  return 0;
          }

Output:

TestProgram this is a test 100 -1

Received 7 arguments...

argument 0: TestProgram.exe
argument 1: this
argument 2: is
argument 3: a
argument 4: test
argument 5: 100
argument 6: -1

Example: Sum of the command line arguments

Code:

#include <iostream.h>
#include <cstdlib>
int main(int argc, char **argv)
  {
        double sum=0;
        int i=0;
    if(argc>1)
        {
                for(i=1;i<argc;i++)
                sum+= atof(argv[i]);
                cout<< "The sum is  " << sum;
        }
        else
                cout<< “No arguments supplied”;
        return 0;
}

OUTPUT:- SUM 4.5 5.5

The sum is 10.0000

Implementing Command Line Argument in JAVA



In Java the command line arguments are stored as strings in a String array which is then passed to the main() function as a parameter.

The prototype of main() function:

Public static void main(String args[]) args is a String array holding the command line arguments as strings.

Here args[0] is the argument which follows the program name to a java command unlike C where argv[0] represents the program name.

Example: Display all command-line arguments

Code:

class CmndLine {
  public static void main(String args[]) {
    for(int i=0; i<args.length; i++)
      System.out.println("args[" + i + "]: " + args[i]);
  }
}

Executing this program:-

java CommandLine This is a test 100 -1

Output:

args[0]: This
args[1]: is
args[2]: a
args[3]: test
args[4]: 100
args[5]: -1

If the above program is executed in the following way:

java CommandLine “This is a test 100 -1”

The entire text within the double quotation marks would be treated as a single argument.

Output:

args[0]: This is a test 100 -1

In Java all command line arguments are passed as Strings. If an application needs to support numeric command line arguments, it must convert a String argument that represents a number to a numeric value such as “55” to a numeric value using appropriate Java built in methods such as Integer.ParseInt() method which converts a String argument to its corresponding integer value.

Example:

Code:

int numArg;
if (args.length > 0) {
            try {
                        numArg = Integer.parseInt(args[0]);
            } catch (NumberFormatException e) {
                        System.err.println("Argument must be an integer");
                        System.exit(1);
            }
}

parseInt method throws a NumberFormatException if the format of args[0] isn't in a form to be converted to a integer or is in invalid form

All of the Number classes in Java — Integer, Float, Double, and so on have their corresponding parseXXX methods that convert a String representing a number to an object of their type.

IBNSC 24Apr2010 12:09

Re: Command Line Argument
 
nice info

shabbir 3May2010 13:15

Re: Command Line Argument
 
Nominate this article for Article of the month - Apr 2010

shabbir 16May2010 19:40

Re: Command Line Argument
 
Vote for this article for Article of the month - Apr 2010


All times are GMT +5.5. The time now is 12:20.