Some programs need to access the arguments that were specified to them on the commandline. For example, emacs can take a filename:
% emacs myfile.txt
or you might give ls a flag and a directory:
% ls -l hw2
Here, "myfile.txt", "-l" and "hw2"
are all program arguments. Arguments are typically separated
by spaces on the commandline.
The way that a program can access its arguments is via parameters to
the function main(). So far, we have been declaring our
main()'s without parameters:
int main()
{
...
If we want access to the program's arguments, we need 2 parameters (in this exact order):
int main(int argc, char *argv[])
{
...
Here,
argv
as an array.
So, suppose main()'s parameters are declared as above
and we ran such a program:
% path/a.out this that another
then argc and argv would be as follows:
argc ----- | 4 | ----- argv ----- | | ---------------------------------------------- 0| --+--> | p | a | t | h | / | a | . | o | u | t | \0 | | | ---------------------------------------------- ----- | | ---------------------- 1| --+--> | t | h | i | s | \0 | | | ---------------------- ----- | | ---------------------- 2| --+--> | t | h | a | t | \0 | | | ---------------------- ----- | | ---------------------------------- 3| --+--> | a | n | o | t | h | e | r | \0 | | | ---------------------------------- -----
So, for example, the word "another" will be in argv[3].
a.out below:
% a.out foo < infile > outfile
will receive 2 arguments: "a.out" (the command name) and
"foo". The "< infile" and ">
outfile" parts are processed by the operating system before the
program is run.