设为首页 加入收藏

TOP

使用getopt函数对程序参数解析(二)
2014-02-14 12:54:58 来源: 作者: 【 】 浏览:491
Tags:使用 getopt 函数 程序 参数 解析

 

  /*** wingetopt.h ***/

  /*

  POSIX getopt for Windows

  AT&T Public License

  Code given out at the 1985 UNIFORUM conference in Dallas.

  */

  #ifdef __GNUC__

  #include

  #endif

  #ifndef __GNUC__

  #ifndef _WINGETOPT_H_

  #define _WINGETOPT_H_

  #ifdef __cplusplus

  extern "C" {

  #endif

  extern int opterr;

  extern int optind;

  extern int optopt;

  extern char *optarg;

  extern int getopt(int argc, char **argv, char *opts);

  #ifdef __cplusplus

  }

  #endif

  #endif /* _GETOPT_H_ */

  #endif /* __GNUC__ */

  /*** wingetopt.cpp ***/

  /*

  POSIX getopt for Windows

  AT&T Public License

  Code given out at the 1985 UNIFORUM conference in Dallas.

  */

  #include "StdAfx.h"

  #include "wingetopt.h"

  #include

  #define NULL 0

  #define EOF (-1)

  #define ERR(s, c) if(opterr){\

  char errbuf ;\

  errbuf[0] = c; errbuf = '\n';\

  fputs(argv[0], stderr);\

  fputs(s, stderr);\

  fputc(c, stderr);}

  //(void) write(2, argv[0], (unsigned)strlen(argv[0]));\

  //(void) write(2, s, (unsigned)strlen(s));\

  //(void) write(2, errbuf, 2);}

  int opterr = 1;

  int optind = 1;

  int optopt;

  char *optarg;

  int getopt(int argc, char **argv, char *opts)

  {

  static int sp = 1;

  register int c;

  register char *cp;

  if(sp == 1)

  if(optind >= argc ||

  argv[optind][0] != '-' || argv[optind] == '\0')

  return(EOF);

  else if(strcmp(argv[optind], "--") == NULL) {

  optind++;

  return(EOF);

  }

  optopt = c = argv[optind][sp];

  if(c == ':' || (cp=strchr(opts, c)) == NULL) {

  ERR(": illegal option -- ", c);

  if(argv[optind][++sp] == '\0') {

  optind++;

  sp = 1;

  }

  return(' ');

  }

  if(*++cp == ':') {

  if(argv[optind][sp+1] != '\0')

  optarg = &argv[optind++][sp+1];

  else if(++optind >= argc) {

  ERR(": option requires an argument -- ", c);

  sp = 1;

  return(' ');

  } else

  optarg = argv[optind++];

  sp = 1;

  } else {

  if(argv[optind][++sp] == '\0') {

  sp = 1;

  optind++;

  }

  optarg = NULL;

  }

  return(c);

  }

  以上的wingetopt.h与wingetopt.cpp来自 这里另外也可以看看codeproject上的一个实现 XGetopt

      

首页 上一页 1 2 3 4 下一页 尾页 2/4/4
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇C优化篇之优化内存访问 下一篇全志A10_linux3.0内核编译记录

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: