Latest web development tutorials

C command line parameters

When executing the program, the command line can pass values ​​to the C program. These values are referred to ascommand-line arguments, they are important to the program, especially if you want to control from an external program, not in the code when these values are hard-coded, it is particularly important.

Command line parameters is to use main () function to process parameters,wherein, argc refers to the number of passed parameters,argv [] is an array of pointers, each of the parameters passed to the program point. Here is a simple example, to check whether there is a command line argument is provided, and perform the appropriate action according to the parameters:

#include <stdio.h>

int main( int argc, char *argv[] )  
{
   if( argc == 2 )
   {
      printf("The argument supplied is %s\n", argv[1]);
   }
   else if( argc > 2 )
   {
      printf("Too many arguments supplied.\n");
   }
   else
   {
      printf("One argument expected.\n");
   }
}

Use a parameter, compile and execute the above code, it will produce the following results:

$./a.out testing
The argument supplied is testing

Two arguments, compile and execute the above code, it will produce the following results:

$./a.out testing1 testing2
Too many arguments supplied.

Do not pass any parameters, compile and execute the above code, it will produce the following results:

$./a.out
One argument expected

It should benoted, argv [0] to store the name of the program,argv [1] is a pointer to the first command-line argument pointer, * argv [n] is the last parameter. If no arguments, argc will be 1. Otherwise, if you pass aparameter, argc would be set to 2.

Between a plurality of command line parameters separated by a space, but if the argument itself with space, then pass parameters when parameters should be placed in double quotes "" or single quotes '' inside. Let's rewrite the above example, there is a space, then you can the view, put them in double or single quotes. "" "." Let's rewrite the above example, to pass a program placed inside double quotes command line parameters:

#include <stdio.h>

int main( int argc, char *argv[] )  
{
   printf("Program name %s\n", argv[0]);
 
   if( argc == 2 )
   {
      printf("The argument supplied is %s\n", argv[1]);
   }
   else if( argc > 2 )
   {
      printf("Too many arguments supplied.\n");
   }
   else
   {
      printf("One argument expected.\n");
   }
}

Use a simple parameter separated by spaces, parameters enclosed in double quotes, compile and execute the above code, it will produce the following results:

$./a.out "testing1 testing2"

Progranm name ./a.out
The argument supplied is testing1 testing2