Command Line Arguments
This material is from chapter 6.
As we have seen, many systems programs use command line arguments.
It is easy to implement command line arguments.
First the big lie
We have lied to you for a while now about main in c/c++
Main has no arguments
int main()
In fact main can have 0 or two arguments.
int main(int argc, char * argv[])
or
int main (int argc, char ** argv)
argv
this is an array of c style strings.
Each is null terminated.
The last entery is a nullptr as well.
The first entry is special, it is the name of the program that is being executed.
argc
this is the number of entries in argv
argv[argc] = nullptr
Look at
args.C
Using argv and argc
argv[0] can be used to determin the behavior of a program.
ls -il /usr/bin/g++ /usr/bin/c++
State variables
Set a variable with a default value.
Search for the corresponding flag
If the flag is set, change the variable to the new value.
Execute the program with behavior based on the variables.
If an unknown flag is given, a required flag is not given or an invalid value is given
Complain to the user about the problem.
If you can recover, or use a resonable default continue
If you can not recover, exit.
Types of command line arguments
Flags : turn an option on or off
Values Setting: normally take at least one argument
Look at the manpage for sort.
-l
--word
-l value
--word=value
-lvalue is also acceptable.
The keys are strange
sort
this file
sort -Vrk2,2 -k 1,1 --key=3nr people
Note
Multiple single character flags can be groupd
-Vr
A flag needing an argument can end the list
-Vrk2,2
A single argument character can have a space or not to the next argument.
-- is used for words (readability)
-- seem to require --flag=value
really old commands do not rquire the - (see tar)
You can simplify this by not allowing combination of flags.
strcmp
to compare c style strings.
Write a program that will
print help with -h or --help
change the greeting string -gstring, -g string, --greeting=string, --greeting string
say hello n times with -m n
reverse the greeting string with -r or --reverse
print letters a through b of the greeting -x a,b , --range=a,b
Look at
args2.C
Appendix B of the book discusses
getopt
a tool for parsing command line arguments.