Command Line Arguments

"Real Programmers always confuse Christmas and Halloween because OCT 31 == DEC 25" -- Andrew Rutherford

Command Line Arguments

Usually, we see main prototyped as:
void main(void);
or
int main(void);
However, main is sort of overloaded to take parameters as well:
int main(int argc, char *argv[]);
int main(int argc, char **argv);
As we've seen with arrays as parameters, the declarations above are equivalent. This trivial program simply prints out each argument:
void main(int argc, char *argv[])
{
  int i;
  for (i = 0; i < argc; i++)
    printf("arg%i = %s\n", i, argv[i]);
}
If our program was named foo.exe and we were to invoke the program like this:
foo one two three 911
we would see something like this printed out:
foo
one
two
three
911
Another example:
foo one "two three" four 911
foo
one
two three
four
911
Within Visual Studio we see:
E:\Data\Courses\Summer2004\CS220\Code\Chapter16\RTL\Debug\foo.exe
one
two three
four
911
because the IDE invokes the program using the entire path.

A more compact way of printing the arguments using pointers instead of subscripts:

void main(int argc, char **argv)
{
  while (*argv)
    printf("%s\n", *argv++);
}
Diagram of the arguments when invoked as:
foo one "two three" four 911


Note: Because argv is an array of pointers to characters (strings), you can only pass strings to a program. If you want to use the parameter as a number, you will have to convert it from a string to a number yourself. See the Data Conversion section in the C Runtime Library.

Example driver code for the FileCopy project:


#include <stdio.h>  /* printf */
#include <stdlib.h> /* atoi   */
#include <time.h>   /* time_t, time */

#include "FileCopy.h"

int main(int argc, char **argv)
{
  unsigned bufsize = 100; /* default size if not provided */
  int reads;
  clock_t start, end;

    /* If less than 2 arguments are provided, remind the user */
    /* how to use the program.                                */
  if (argc < 3)
  {
    printf("\n");
    printf("Usage: FileCopy {source} {destination} [buffersize]\n");
    printf("       Default buffer size is 100 bytes.\n\n");
    return -1;
  }

    /* If the user provides a size, use it */
  if (argc > 3)
    bufsize = atoi(argv[3]);

  start = clock();
  reads = FileCopy(argv[1], argv[2], bufsize);
  end = clock();

  if (reads == E_BAD_SOURCE)
    printf("Unable to open file for read: %s\n", argv[1]);
  else if (reads == E_BAD_DESTINATION)
    printf("Unable to open file for write: %s\n", argv[2]);
  else if (reads == E_NO_MEMORY)
    printf("Unable to allocate buffer of size %u\n", bufsize);
  else
    printf("With bufsize of %i, number of reads: %i. Total time: %i ms.\n", bufsize, reads, end - start);

  return 0;
}

Command Line Paramters for Some Game Engines