Accepting Command Line Arguments in C Using Argc and Argv
Accepting Command Line Arguments in C Using Argc and Argv
The integer, argc is the argument count. It is the number of arguments passed into
the program from the command line, including the name of the program.
The array of character pointers is the listing of all the arguments. argv[0] is the
name of the program, or an empty string if the name is not available. After that,
every element number less than argc is a command line argument. You can use
each argv element just like a string, or use argv as a two dimensional array.
argv[argc] is a null pointer.
How could this be used? Almost any program that wants its parameters to be set
when it is executed would use this. One common use is to write a function that
takes the name of a file and outputs the entire text of it onto the screen.
#include <stdio.h>
This program is fairly short, but it incorporates the full version of main and even
performs a useful function. It first checks to ensure the user added the second
argument, theoretically a file name. The program then checks to see if the file is
valid by trying to open it. This is a standard operation, and if it results in the file
being opened, then the return value of fopen will be a valid FILE*; otherwise, it will
be 0, the NULL pointer. After that, we just execute a loop to print out one character
at a time from the file. The code is self-explanatory, but is littered with comments;
you should have no trouble understanding its operation this far into the tutorial.