标签:
#include <unistd.h> extern char *optarg; extern int optind, extern int opterr, extern int optopt; int getopt(int argc, char * const argv[], const char *optstring);
定义了四个全局变量:optarg是选项的参数指针,optind记录目前查找的位置,当opterr = 0时,getopt不向stderr输出错误信息。当命令选项字符不包括在optstring中或者缺少必要的参数时,该选项存储在optopt中,getopt返回 ‘?‘
#include <stdio.h> #include <stdlib.h> #include <unistd.h> int main(int argc, char **argv) { int opt = 0; while ((opt = getopt(argc, argv, "if:?lr::")) != -1) { switch(opt) { case ‘i‘: case ‘l‘: printf("option: %c\n", opt); break; case ‘f‘: printf("filename: %s\n", optarg); break; case ‘r‘: printf("arg:%s\n", optarg); break; case ‘:‘: printf("option needs a value\n"); break; case ‘?‘: printf("unknow option: %c\n", optopt); break; } } for (; optind < argc; optind++) { printf("argument: %s\n", argv[optind]); ar return 0; }
struct option { char *name; int has_arg; int *flag; int val; };
struct option longopts[] = { {"initialize", 0, NULL, ‘i‘}, {"filename", 1, NULL, ‘f‘}, {"list", 0, NULL, ‘l‘}, {"restart", 0, NULL, ‘r‘} };
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #define _GNU_SOURCE #include <getopt.h> int main(int argc, char **argv) { int opt; struct option longopts[] = { {"initialize", 0, NULL, ‘i‘}, {"filename", 1, NULL, ‘f‘}, {"list", 0, NULL, ‘l‘}, {"restart", 0, NULL, ‘r‘} }; while ((opt = getopt_long(argc, argv, ":if:lr", longopts, NULL)) != -1) { switch(opt) { case ‘i‘: case ‘l‘: case ‘r‘: printf("option: %c\n", opt); break; case ‘f‘: printf("filename: %s\n", optarg); break; case ‘:‘: printf("option needs a value\n"); break; case ‘?‘: printf("unknow option: %c\n", optopt); break; } } for (; optind < argc; optind++) { printf("argument: %s\n", argv[optind]); } return 0; }
标签:
原文地址:http://www.cnblogs.com/shenlinken/p/5791428.html