This is a creation in Article, where the information may have evolved or changed.
The getopt () function in the C language provides a great convenience for command parameter acquisition, similar to the flag function in Golang.
C Language 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) {SWITC H (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 = ' + '; 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 the host address in Parameters"); printf ("\ n"); Return-2; }return 0;}
Go language Flag
go的flag相比于c的getopt使用起来简单很多。
cfgPath := flag.String("c","/etc/cfg.toml","cfg path")nowaitFlag :=flag.Bool("w",false,"do not wait")
The first command in the function is the indicator in "-C", "-w", the second is the default value, and the third is the description. No matter the order, as long as the normal appearance can be resolved.