Command Line Arguments
Command Line Arguments
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
#include <stdio.h>
main( int argc, char *argv[]) { FILE *in_file, *out_file, *fopen(); int c; if( argc != 3 ) { printf("Incorrect, format is FCOPY source dest\n"); exit(2); }
in_file = fopen( argv[1], "r"); if( in_file == NULL ) printf("Cannot open %s for reading\n", argv[1]); else { out_file = fopen( argv[2], "w"); if ( out_file == NULL ) printf("Cannot open %s for writing\n", argv[2]); else { printf("File copy program, copying %s to %s\n", argv[1], argv[2]); while ( (c=getc( in_file) ) != EOF ) putc( c, out_file ); putc( c, out_file); /* copy EOF */ printf("File has been copied.\n"); fclose( out_file); } fclose( in_file); } }
SYSTEM CALLS Calls may be made to the Operating System to execute standard OPsys calls, eg,
#include <process.h> main() /* SYS.C */ { char *command = "dir"; system( "cls" ); system( command ); }
Do not use this method to invoke other programs. Functions like exec() and spawn() are used for this.