Handout 6

Using Command Line Arguments


Introduction

During the compilation process, Turbo C turns your C source code first into an .obj form and the links the .obj file to form an .exe file. This .exe file by default is stored in the /tc/bin subdirectory. You can use this .exe file as a stand alone program.

It's possible to pass parameters to your program using the parameters arc and argv in the main function. The following code illustrates the usage.

/* Example showing the use of command line parameters */

#include <iostream.h>

/*      the command line variables argc and argv are specified as the
        parameter values for the main function.

        argc is an int variable that contains the count of command line
        arguments.  The count in argc always includes the name of the
        procedure invoked.  The following examples illustrate:

        command line                  argc
        ------------                  ----
        stuff                            1
        stuff c:\temp\a.txt              2
        stuff a c d a.txt                5

        argv is a pointer to an array that contains the actual command
        line arguments.  You can access these within your program and
        process them.  Note that argv[0] contains the name of the invoked
        procedure.  The following examples illustrate:

        command line         argv[0]      argv[1]     argv[2]      argv[3]
        ------------         -------      -------     -------      ------- 
        stuff                stuff
        stuff a.txt          stuff        a.txt
        stuff a c a.txt      stuff        a           c            a.txt

*/

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

  int i;

  cout << "You have called " << argv[0] << " with "
                 << (argc-1) << " arguments" << endl;

  if(argc > 1)
         for(i=1; i<argc; i++)
           cout << "Argument " << i << ":" << argv[i] << endl;  
  
  return 0;

}