您的位置:首页 > 编程语言 > Go语言

C 语言getopt与go语言flag获取命令参数

2017-08-05 14:22 726 查看
C语言中的getopt()函数为命令参数的获取提供了很大便利,与golang中的flag功能类似。


C语言getopt

下面以ssh中获取主机名/ip和用户名为例来示例如何使用getopt().


int get_user_host(int ac, char **av, char *host, char *user){

char *p, *cp;
extern int optind;
int opt;

again:
while ((opt = getopt(ac, av, "1246AaCfgKkMNnqsTtVvXxYyb:c:D:e:F:I:i:L:l:m:O:o:p:R:S:W:w:")) != -1){

switch (opt){
case '1':
break;
case '2':
break;
case '4':
break;
case '6':
break;
case 'A':
break;
case 'a':
break;
case 'C':
break;
case 'f':
break;
case 'g':
break;
case 'K':
break;
case 'k':
break;
case 'M':
break;
case 'N':
break;
case 'n':
break;
case 'q':
break;
case 's':
break;
case 'T':
break;
case 't':
break;
case 'V':
break;
case 'v':
break;
case 'X':
break;
case 'x':
break;
case 'Y':
break;
case 'y':
break;
case 'b':
break;
case 'c':
break;
case 'D':
break;
case 'e':
break;
case 'F':
break;
case 'I':
break;
case 'i':
break;
case 'L':
break;
case 'l':
break;
case 'm':
break;
case 'O':
break;
case 'o':
break;
case 'p':
break;
case 'R':
break;
case 'S':
break;
case 'W':
break;
case 'w':
break;
default:
return -3;
}
}

ac -= optind;
av += optind;

if (ac > 0 && strlen(host)==0 &&  **av != '-') {
if (strrchr(*av, '@')) {
p = strdup(*av);
cp = strchr(p, '@');
if (cp == NULL || cp == p){
printf("can not find username nearby @");
printf("\n");
return -1;;
}
*cp = '\0';
user = strcpy(user, p);
host = strcpy(host,++cp);
} else{
host = strcpy(host, *av);
}
if (ac >1 ){
optind  = 1;
goto again;
}
ac--, av++;
}
if (strlen(host)==0){
printf("can not find host address in parameters");
printf("\n");
return -2;
}
return 0;
}


go语言flag

go的flag相比于c的getopt使用起来简单很多。


cfgPath := flag.String("c","/etc/cfg.toml","cfg path")
nowaitFlag :=flag.Bool("w",false,"do not wait")


函数中第一个命令是”-c”、”-w”中的指示词,第二个为默认值,第三个为说明。无论顺序,主要正常出现就能解析。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息