为梦而战
全部博文(185)
分类: C/C++
2015-01-16 08:42:56
原文地址:getopt ,getopt_long使用方法 作者:lzj123
#include#include #include int main(int argc, char *argv[ ]) { int c; int flg = 0; char filename[256]; char testdata[256]; if (argc < 2) { printf("usage:%s [-f filename] [-n] testdata\n", argv[0]); return -1; } opterr = 0; while ((c = getopt(argc, argv, "f:n")) != -1) { switch (c) { case 'f': strncpy(filename, optarg, sizeof(filename)-1); break; case 'n': flg = 1; break; case '?': default: printf("usage:%s [-f filename] [-n] testdata\n", argv[0]); return -1; } } if (argv[optind] == NULL) { printf("usage:%s [-f filename] [-n] testdata\n", argv[0]); return -1; } else { strncpy(testdata, argv[optind], sizeof(testdata)-1); } printf("fliename:%s flg:%d testdata:%s\n", filename, flg, testdata); return 0; }
#include/* for printf */ #include /* for exit */ #include int main(int argc, char **argv) { int c; int digit_optind = 0; int flag = 0; while (1) { int this_option_optind = optind ? optind : 1; int option_index = 0; static struct option long_options[] = { {"add", required_argument, 0, 0 }, {"append", no_argument, 0, 0 }, {"delete", required_argument, 0, 0 }, {"verbose", no_argument, 0, 0 }, {"create", required_argument, 0, 'c'}, {"file", required_argument, 0, 'f'}, {0, 0, 0, 0 } }; c = getopt_long_only(argc, argv, "abc:d:f:012", long_options, &option_index); if (c == -1) break; switch (c) { case 0: printf("option %s", long_options[option_index].name); if (optarg) printf(" with arg %s", optarg); printf("\n"); break; case '0': case '1': case '2': if (digit_optind != 0 && digit_optind != this_option_optind) printf("digits occur in two different argv-elements.\n"); digit_optind = this_option_optind; printf("option %c\n", c); break; case 'a': printf("option a\n"); break; case 'b': printf("option b\n"); break; case 'c': printf("option c with value '%s'\n", optarg); break; case 'd': printf("option d with value '%s'\n", optarg); break; case 'f': printf("option f with value '%s'\n", optarg); break; case '?': break; default: printf("?? getopt returned character code 0%o ??\n", c); } } if (optind < argc) { printf("non-option ARGV-elements: "); while (optind < argc) printf("%s ", argv[optind++]); printf("\n"); } exit(EXIT_SUCCESS); }