|
|
发表于 2006-1-17 11:05:05
|
显示全部楼层
from beginning linux programming 3rd
To help us adhere to these guidelines, Linux gives us the getopt facility, which supports the use of
options with and without values and is simple to use.
#include <unistd.h>
int getopt(int argc, char *const argv[], const char *optstring);
extern char *optarg;
extern int optind, opterr, optopt;
The getopt function takes the argc and argv parameters as passed to the program’s main function and
an options specifier string that tells getopt what options are defined for the program and whether they
have associated values. The optstring is simply a list of characters, each representing a single character
option. If a character is followed by a colon, it indicates that the option has an associated value that will
be taken as the next argument. The getopts command in bash performs a very similar function.
For example, the following call would be used to handle our preceding example
getopt(argc, argv, “if:lr”);
It allows for simple options -i, -l , -r, and -f, followed by a filename argument. Calling the command
with the same parameters but in a different order will alter the behavior. Try it out when we get to the
sample code in the next “Try It Out” section in this chapter.
:表示指定的参数后面要求一个值,如:
xx -i -f filename -l -r
那个值可以用 optarg 取到。
btw, 要勾中"在文字中禁用表情符号" |
|