Command Line Arguments in C
Using argc and argv
To execute the file-copy programs we are required to first type the program, compile it, and then execute it. This program can be improved in two ways:
(a) There should be no need to compile the program every time to use the file-copy utility. It means the program must be executable at command prompt (A> or C> if you are using MS-DOS, Start | Run dialog if you are using Windows and $ prompt if you are using Unix).
(b) Instead of the program prompting us to enter the source and target filenames, we must be able to supply them at command prompt, in the form:
filecopy sourcefile.txt targetfile.txt
where, sourcefile.txt is the source filename and targetfile.txt is the target filename.
The first improvement is simple. In MS-DOS, the executable file (the one which can be executed at command prompt and has an extension .EXE) can be created in Turbo C/C++ by using the key F9 to compile the program. In VC++ compiler under Windows same can be done by using F7 to compile the program. Under Unix this is not required since in Unix every time we compile a program we always get an executable file.
The second improvement is possible by passing the source filename and target filename to the function main( ). This is illustrated below:
#include "stdio.h" int main(int argc, char *argv[]) { FILE *fs, *ft; char ch; if (argc != 3) { puts("Improper number of arguments"); exit(1); } fs = fopen(argv[1], "r"); if (fs == NULL) { puts("Cannot open source file"); exit(1); } ft = fopen(argv[2], "w"); if (ft == NULL) { puts("Cannot open target file"); fclose(fs); exit(1); } while (1) { ch = fgetc(fs); if (ch == EOF) break; else fputc(ch, ft); } fclose(fs); fclose(ft); printf("Completed copying..."); return 0; }
the above program after compiling will be executed as :
The arguments that we pass on to main( ) at the command prompt are called command line arguments. The function main( ) can have two arguments, traditionally named as argc and argv. Out of these, argv is an array of pointers to strings and argc is an int whose value is equal to the number of strings to which argv points. When the program is executed, the strings on the command line are passed to main( ). More precisely, the strings at the command line are stored in memory and address of the first string is stored in argv[0], address of the second string is stored in argv[1] and so on. The argument argc is set to the number of strings given on the command line. For example, in our sample program, if at the command prompt we give,
D:\>file sourcefile.txt targetfile.txt
then,
argc would contain 3
argv[0] would contain base address of the string “file”
argv[1] would contain base address of the string “sourcefile.txt”
argv[2] would contain base address of the string “targetfile.txt”