C语言main函数参数解析代码模板
#include "stdio.h" int main(int argc, char **argv) { char *arg; for (argc--, argv++; argc > 0 && argv != NULL; argc--, argv++) { arg = *argv; if (arg[0] == '-') { if (arg[1] == 0 || arg[2] != 0) { fprintf(stderr, "Ignoring unrecognized param: %s\n", arg); continue; } switch (arg[1]) { case 's': case 'S': if (argc == 1) { fprintf(stderr, "Expecting output filename. -s is igored\n"); } else { fprintf(stdout, "-s recognized, argv[1]:%s\n", argv[1]); --argc; ++argv; } break; case 't': case 'T': if (argc == 1) { fprintf(stderr, "Expecting output filename. -t is igored\n"); } else { fprintf(stdout, "-t recognized, argv[1]:%s\n", argv[1]); --argc; ++argv; } break; default: fprintf(stderr, "Ignoring unrecognized param: %s\n", arg); } } else { fprintf(stdout, "default, argv:%s\n", *argv); } } return 0; }