Command Line Arguments

Some C programs can behave in many different ways, based on the users request. For example, if we use the "ls" command to list files in a directory, we get one format of data back. If we use "ls -l" we get a long listing, which is a different format. The "-l" is considered a command line argument. The C program must "parse" the command line arguments (which are given to the program as a list of strings) and transform this type of data into a form useful in "guiding" the program to execute in the manner specified by the user.

Command Line Args

Many programs have command line args that tell the program how to behave:


  % ls -l

  % g++ -g -Wall

  % grep -v abc

      

In C, when you run a program via the linux command line, you can look at these command line values and alter the behavior of your program as well.

The first step to tell a C program to "get" the command line values is to change the signature of the main function, as follows:

	

int
main( int number_of_args, char* list_of_args[] )
{
  ...
}


//
// Note: Often you will see "traditional" programs using the more 
// archaic (if more concise) "Lingo" and syntax for 
// these values (argc and argv)
//

int
main( int argc, char** argv )                    
{
  ...
}
	
      
  1. number_of_args : the total number of "values" on the command line.

    Note: The name of the program is counted and is the first value.

    Note: Values are defined by lists of characters separated by whitespace.

  2. list_of_args : this is an array of strings.

    Note: The array has a length defined by the number_of_args parameter.

When the program is invoked with "values" after the name of the program, they are stored in the list_of_args. We normally use a loop to "search" through this list of strings to find (and set) the state of the program.

Here is a sample program to print out all the information "given" to the program:

	

int
main( int number_of_args, char* list_of_args[] )
{
  for ( int i=0; i<number_of_args; i++)
    {
      printf("the %2d arg is: %s\n", i, list_of_args[i]);
    }
}
	
      

Processing Command Line Args

Usually, you will create a function in C which reads through all the command line args and returns the state.

For simple cases, where the command line args are well defined, this can be done in the first few lines of code of the main function:

	
// example 1

int
main( int number_of_args, char* list_of_args[] )
{
  if ( number_of_args != 1 )
    {
      printf("this program does not take any args!\n");
      exit(-1);
    }
}

// example 2

int
main( int number_of_args, char* list_of_args[] )
{
  char invoke_command[] = "./program_name #";
  int repeat;

  if ( number_of_args != 2 )
    {
      printf("Please use: %s\n", invoke_command);
      exit(-1);
    }
  
   // read the second arg and put the value in a number variable:
   sscanf(list_of_args[1], "%d", &repeat);
												    
}
	
      

Back to Topics List