前言
在linux中,经常需要各种命令,通常情况下都会带各种参数,而这些参数是如何解析的呢?通常使用GNU
C提供的函数getopt、getopt_long、getopt_long_only函数来解析命令行参数。
一、关于命令行参数
命令行参数可以分为两类,一类是短选项,一类是长选项,短选项在参数前加一杠"-“,长选项在参数前连续加两杠”–",如下表(ls 命令参数)所示,其中-a,-A,-b
都表示短选项,--all,--almost-all, --author
都表示长选项。他们两者后面都可选择性添加额外参数。比如--block-size=SIZE
,SIZE便是额外的参数。
LS(1) User Commands LS(1)
NAME
ls - list directory contents
SYNOPSIS
ls [OPTION]... [FILE]...
DESCRIPTION
List information about the FILEs (the current directory by default).
Sort entries alphabetically if none of -cftuvSUX nor --sort is speci‐
fied.
Mandatory arguments to long options are mandatory for short options
too.
-a, --all
do not ignore entries starting with .
-A, --almost-all
do not list implied . and ..
--author
with -l, print the author of each file
-b, --escape
print C-style escapes for nongraphic characters
--block-size=SIZE
scale sizes by SIZE before printing them; e.g., '--block-size=M'
prints sizes in units of 1,048,576 bytes; see SIZE format below
二、getopt_long函数
getopt
函数只能处理短选项,而getopt_long
函数两者都可以,可以说getopt_long
已经包含了getopt_long
的功能。因此,这里就只介绍getopt_long
函数。而getopt_long
与getopt_long_only
的区别很小,等介绍完getopt_long
,在提起会更好。
#include <unistd.h>
extern char *optarg;
extern int optind, opterr, optopt;
#include <getopt.h>
int getopt(int argc, char * const argv[],const char *optstring);
int getopt_long(int argc, char * const argv[], const char *optstring, const struct option *longopts, int *longindex);
int getopt_long_only(int argc, char * const argv[], const char *optstring, const struct option *longopts, int *longindex);
参数以及返回值介绍(以上三个函数都适用):
1、argc和argv和main函数的两个参数一致。
2、optstring: 表示短选项字符串。
形式如“
a:b::cd:
“,分别表示程序支持的命令行短选项有-a、-b、-c、-d,冒号含义如下:
(1)只有一个字符,不带冒号——只表示选项, 如-c
(2)一个字符,后接一个冒号——表示选项后面带一个参数,如-a 100
(3)一个字符,后接两个冒号——表示选项后面带一个可选参数,即参数可有可无, 如果带参数,则选项与参数直接不能有空格形式应该如-b200
3、longopts:表示长选项结构体。结构如下:
struct option
{
const char *name;
int has_arg;
int *flag;
int val;
};
eg:
static struct option longOpts[] = {
{ "daemon", no_argument, NULL, 'D' },
{ "dir", required_argument, NULL, 'd' },
{ "out", required_argument, NULL, 'o' },
};