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”中的指示词,第二个为默认值,第三个为说明。无论顺序,主要正常出现就能解析。
相关文章推荐
- go 语言 获取物理机器主要参数
- python通过getopt模块获取执行命令参数
- GO语言flag参数解析
- go语言中flag的用法——参数解析
- Go语言中使用flag包对命令行进行参数解析的方法
- Go语言中一些不常见的命令参数详解
- golang go 语言在 window下执行命令 获取本地ip
- Go语言的参数解析(flag)
- python通过getopt模块如何获取执行的命令参数详解
- Go语言中读取命令参数的几种方法总结
- 使用getopt_long()从命令行获取参数,struct option
- Go语言学习之flag包(The way to go)
- NodeJS获取命令行后面的参数
- getopt命令--用于shell脚本获取命令行选项
- 使用getopt_long()从命令行获取参数
- 一行命令获取当前JVM所有可设置的参数以及当前默认值
- go语言获取本地IP地址(图形界面)
- 在Python中调用shell命令及 获取python命令中的参数
- Go语言圣经 - 习题 - 1.6. 并发获取多个URL
- go语言:函数参数传递详解