July 10th, 2003, 10:45 AM
This applies to C programs both under UNIX/Linux and under Windows/DOS: the command-line arguments are passed to the program through the main() function arguments argc and argv (terminology police, please go easy on me here; I haven't had my morning coffee yet).
char *argv is an array of character strings. Basically, the command is tokenized (split up) using white space as the delimiter and each token is placed in argv ("arg vector") in the order that they occur. int argc ("arg count") is the number of entries in argv. The entries are:
argv -- the name of the program
argv -- the first argument
argv -- the second argument
Since you write the program, you define what kind of data is expected in each argument. For example, in my earlier experiments in developing a broadcast server, I gave it this syntax:
bctimed <IP Address> <Port> <Send String>
So this command:
bctimed 192.168.5.240 7 "This is a test"
results in these values:
argc = 4
argv = "bctimed"
argv = "192.168.5.240"
argv = "7"
argv = "This is a test"
One of the implications of this is that if you pass the program a numeric argument, it will receive it as a string, so you will need to convert it to numeric, as with the function atoi().
And, of course, if your program does not accept arguments from the command line, then you can always declare the main() function as:
Hope that explains.
Options, such as "-b" , are also passed in to the program in this manner. There is a great C function, getopt, that is very useful in extracting options, option variables (eg, "-o prog" as in gcc -o prog main.c), and the arguments as described above. So far, I have not seen it in any Windows/DOS C compiler I've used and it was missing from the MinGW port of gcc that I use (even though the header file was there). If you're going to be doing much with command-line options and parameters, you might want to look into it. I found a source listing online and added it to my MinGW library.
Last edited by dwise1_aol : July 10th, 2003 at 10:49 AM.