[root@rhel74 c]# cat getopt.c
#include <unistd.h>
#include <stdio.h>
int
main(int argc, char *argv[])
{
int opt;
while((opt = getopt(argc, argv, "af:tx")) != -1){
switch(opt){
case 'a':
printf("opt=%c\n", opt);
printf("optind=%d\n", optind);
printf("optopt=%d\n", optopt);
printf("optarg=%s\n", optarg);
printf("opterr=%d\n", opterr);
break;
case 'f':
printf("opt=%c\n", opt);
printf("optind=%d\n", optind);
printf("optopt=%d\n", optopt);
printf("optarg=%s\n", optarg);
printf("opterr=%d\n", opterr);
break;
case 't':
printf("opt=%c\n", opt);
printf("optind=%d\n", optind);
printf("optopt=%d\n", optopt);
printf("optarg=%s\n", optarg);
printf("opterr=%d\n", opterr);
break;
case 'x':
printf("opt=%c\n", opt);
printf("optind=%d\n", optind);
printf("optopt=%d\n", optopt);
printf("optarg=%s\n", optarg);
printf("opterr=%d\n", opterr);
break;
case '?':
printf("opt=%c\n", opt);
printf("optind=%d\n", optind);
printf("optopt=%d\n", optopt);
printf("optarg=%s\n", optarg);
printf("opterr=%d\n", opterr);
break;
}
}
return 0;
}
[root@rhel74 c]# ./getopt -a -b -c -f asdf -- -x
opt=a
optind=2
optopt=0
optarg=(null)
opterr=1
./getopt: invalid option -- 'b'
opt=?
optind=3
optopt=98
optarg=(null)
opterr=1
./getopt: invalid option -- 'c'
opt=?
optind=4
optopt=99
optarg=(null)
opterr=1
opt=f
optind=6
optopt=99
optarg=asdf
opterr=1
[root@rhel74 c]# cat getopt_long.c
#include <unistd.h>
#include <stdio.h>
#include <getopt.h>
int
main(int argc, char *argv[])
{
int opt;
int flag1;
int flag2;
int longindex;
const struct option longopts[] = {
{"create", no_argument, 0, 'c'},
{"delete", required_argument, 0, 'd'},
{"setflag", no_argument, &flag1, 3},
{"clrflag", no_argument, &flag2, 0},
{0, 0, 0, 0},
};
opterr = 1;
while((opt = getopt_long(argc, argv, "cd:", longopts, &longindex)) != -1){
switch(opt){
case 'c':
printf("opt=%c\n", opt);
printf("optind=%d\n", optind);
printf("optopt=%d\n", optopt);
printf("optarg=%s\n", optarg);
printf("opterr=%d\n", opterr);
break;
case 'd':
printf("opt=%c\n", opt);
printf("optind=%d\n", optind);
printf("optopt=%d\n", optopt);
printf("optarg=%s\n", optarg);
printf("opterr=%d\n", opterr);
break;
case '?':
printf("opt=%c\n", opt);
printf("optind=%d\n", optind);
printf("optopt=%d\n", optopt);
printf("optarg=%s\n", optarg);
printf("opterr=%d\n", opterr);
break;
}
}
printf("flag1=%d\n",flag1);
printf("flag2=%d\n",flag2);
return 0;
}
[root@rhel74 c]# ./getopt_long --clrflag -d=asdf --setflag --delete=dddd
opt=d
optind=3
optopt=0
optarg==asdf
opterr=1
opt=d
optind=5
optopt=0
optarg=dddd
opterr=1
flag1=3
flag2=0