Loading, please wait...

Command Line Arguments

On many systems, it’s possible to pass arguments to main from a command line by including parameters int argc and char *argv[] in the parameter list of main. Parameter argc receives the number of command-line arguments. Parameter argv is an array of strings in which the actual command-line arguments are stored. Common uses of command-line arguments include passing options to a program and passing filenames to a program. We assume that the executable file for the program is called mycopy.

 

A typical command line for the my copy program on a Linux/UNIX system is $ mycopy input output

 

This command line indicates that file input is to be copied to file output. When the program is executed, if argc is not 3 (mycopy counts as one of the arguments), the program prints an error message and terminates. Otherwise, array argv contains the strings "mycopy", "input" and "output". The second and third arguments on the command line are used as file names by the program. The files are opened using function fopen. If both files are opened successfully, characters are read from file input and written to file output until the end-of-file indicator for file input is set. Then the program terminates. The result is an exact copy of file input.