自己做做练习,呵呵,GNU的getopt可以在glibc中找到,是三个文件:getopt.h getopt.c getopt1.c
getopt.h
extern int optind , optopt, opterr ;
extern char *optarg;
int getopt(int argc, char *argv[], const char *optstring);
getopt.c
#include
int optind = 0, optopt, opterr = 1;
char *optarg;
int getopt(int argc, char *argv[], const char *optstring)
{
static int i = 1;
int j;
char optc;
/* test i */
/* printf("test i = %d\n", i); */
optind = (optind == 0 ? 1 : optind);
if ((argv[optind] != NULL)
&& (strcmp(argv[optind], "--"))
&& (argv[optind][0] == '-')) {
if ((optc = argv[optind][i]) != '\0') {
for (j = 0; optstring[j] != '\0'; j++) {
if (optc == optstring[j])
break;
}
if (optstring[j] == '\0') { /* invalid argument */
optopt = argv[optind][i];
if (optstring[0] != ':' && opterr != 0)
printf("invalid option %c\n", optopt);
if (argv[optind][i+1] == '\0') {
i = 1;
optind++;
} else
i++;
return '?';
}
if (optstring[j+1] == ':') { /* hav argument */
if (argv[optind][i+1] == '\0'
&& ((argv[optind+1] == NULL)
|| argv[optind+1][0] == '-')) {
if (optstring[0] != ':' && opterr != 0)
printf("lost option arg!\n");
if (argv[optind][i+1] == '\0') {
i = 1;
optind++;
} else
i++;
return ':';
}
if (argv[optind][i+1] == '\0') {
optarg = argv[++optind];
} else {
optarg = &argv[optind][i+1];
}
optind++;
i = 1;
return optc;
}
/* no argument */
if (argv[optind][i+1] == '\0') {
i = 1;
optind++;
} else
i++;
return optc;
} /* end if */
} /* end if */
return -1;
}
getopt_test.c
#include
#include "getopt.h"
int main(int argc, char *argv[])
{
char optc;
while ((optc = getopt(argc, argv, ":ab:c")) != -1) {
switch (optc) {
case 'a':
printf("option a, optind = %d\n", optind);
break;
case 'b':
printf("option b, arg = %s, optind = %d\n", optarg, optind);
break;
case 'c':
printf("option c, optind = %d\n", optind);
break;
case ':':
case '?':
break;
default:
return -1;
}
}
return 0;
}
阅读(1877) | 评论(0) | 转发(0) |