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:")) != -){
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 -;
}
}
ac -= optind;
av += optind;
if (ac > && strlen(host)== && **av != '-') {
if (strrchr(*av, '@')) {
p = strdup(*av);
cp = strchr(p, '@');
if (cp == NULL || cp == p){
printf("can not find username nearby @");
printf("\n");
return -;;
}
*cp = '\0';
user = strcpy(user, p);
host = strcpy(host,++cp);
} else{
host = strcpy(host, *av);
}
if (ac > ){
optind = ;
goto again;
}
ac--, av++;
}
if (strlen(host)==){
printf("can not find host address in parameters");
printf("\n");
return -;
}
return ;
}
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”中的訓示詞,第二個為預設值,第三個為說明。無論順序,主要正常出現就能解析。