C- Command Line Arguments

Command Line Arguments

 

Command line arguments allow us to pass information into the program as it is run. For example the simple operating system command type uses command line arguments as follows

c:>type text.dat

where the name of the file to be printed is taken into the type program and the contents of the file then printed out.

In C there are two in-built arguments to the main() function commonly called  argc and argv which are used to process command line arguments.

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

{

}

argc is used to hold the total number of arguments used on the command line which is always at least one because the program name is considered the first command line argument.

argv is a pointer to an array of  pointers to strings where each element in argv points to a command line argument. For example argv[0] points to the first string, the program name.

For Example :- Program to print a name ( saved in name.c ) using command line arguments.

#include <stdio.h>

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

{

if ( argc != 2 )

{

puts( “Missing parameter.  Usage : name yourname” ) ;

exit( 1 );

}

printf( “Hello %s”, argv[1] ) ;

}

 

To run the program one might type

c:\>name sumit

 

For Example :- Program to count down from a given value, the countdown being displayed if the argument  “display” is given.

 

#include <stdio.h>

#include <stdlib.h>

#include <ctype.h>

#include <string.h>

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

{

int disp, count ;

if ( argc < 2 )

{

puts(“Missing Arguments Usage : progname count [display]” );

exit(1) ;

}

if ( argc  > 2 && !strcmp( argv[2], “display” ) )

disp = 1 ;

else

disp = 0 ;

for ( count = atoi( argv[1] ) ; count ; count– )

if ( disp )

printf( “%d\n”, count ) ;

printf( “done\n” ) ;

}

error: Content is protected !!