文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>getopt_long()函数

getopt_long()函数

时间:2009-04-13  来源:nanqihao

getopt 函数

函数定义:
#include
int getopt(int argc, char * const argv[],
        const char *optstring);

extern char *optarg;
extern int optind, opterr, optopt;


#define _GNU_SOURCE
#include

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);


getopt()函数是用来解析命令行参数的。这里,主要解释getopt_long()。

    getopt_long()的头两参数,argc和argv分别是传递给main()的参数的个数和参数数组(和main()的argc和argv是一个概念)。

    getopt_long()中,optstring是一个字符串,表示可以接受的参数。例如,"a:b:cd",表示可以接受的参数是a,b,c,d,其中,a和b参数后面

跟有更多的参数值。(例如:-a host --b name)

    getopt_long()中,参数longopts,其实是一个结构的实例:
struct option {
const char *name;
    //name表示的是长参数名
int has_arg;
    //has_arg有3个值,no_argument(或者是0),表示该参数后面不跟参数值
    //   required_argument(或者是1),表示该参数后面一定要跟个参数值
    //   optional_argument(或者是2),表示该参数后面可以跟,也可以不跟参数值
int *flag;
    //用来决定,getopt_long()的返回值到底是什么。如果flag是null,则函数会返回与该项option匹配的val值
int val;
    //和flag联合决定返回值
}

给个例子:

struct option long_options[] = {
{"a123",       required_argument,      0, 'a'},
{"c123",       no_argument,            0, 'c'},
}

现在,如果命令行的参数是-a 123,那么调用getopt_long()将返回字符'a',并且将字符串123由optarg返回(注意注意!字符串123由optarg带

回!optarg不需要定义,在getopt.h中已经有定义)
那么,如果命令行参数是-c,那么调用getopt_long()将返回字符'c',而此时,optarg是null。

最后,当getopt_long()将命令行所有参数全部解析完成后,返回-1。

看来,我说的有点混乱,那么,看个例子,我相信,代码最能说明问题:

#include
#include
#include
#include

int main( int argc, char **argv )
{

struct option long_options[] = {
   {"a123",       required_argument,      0, 'a'},
   {"c123",       no_argument,            0, 'c'},
}
int opt;

printf("starting... ");

while((opt = getopt_long(argc, argv, "a:c", long_options, NULL)) != -1)
{
switch (opt)
{
case 'a':
    printf("It's a! ");
    printf("string of a:%s ",optarg);
break;
    
case 'c':
    printf("It's c! ");
break;
    
default:
    printf("You should look for help! ");
    exit(1);
break;            
}
}
printf("end... ");
return 0;
}

编译后,假设生成a.out,可以试验一下。
./a.out -a hello -c
输出:
starting...
It's a!
string of a:hello
It's c!
end...

相关阅读 更多 +
排行榜 更多 +
小心突突你

小心突突你

休闲益智 下载
城市卡车模拟器

城市卡车模拟器

体育竞技 下载
小鸭清理

小鸭清理

游戏工具 下载