C Programming

COMMAND LINE ARGUMENTS
It is possible to pass arguments to C programs when they are executed. The brackets which follow main are used for this purpose. argc refers to the number of arguments passed, and argv[] is a pointer array which points to each argument which is passed to main. A simple example follows, which checks to see if a single argument is supplied on the command line when the program is invoked.


	#include <stdio.h>

	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");
	}

Note that *argv[0] is the name of the program invoked, which means that *argv[1] is a pointer to the first argument supplied, and *argv[n] is the last argument. If no arguments are supplied, argc will be one. Thus for n arguments, argc will be equal to n + 1. The program is called by the command line,


	 myprog  argument1


EXERCISE C27
Rewrite the program which copies files, ie, FCOPY.C to accept the source and destination filenames from the command line. Include a check on the number of arguments passed.

Answer


©Copyright B Brown. 1984-1999. All rights reserved.