gcc -g -lm foo.c -o foo
getopt()¾ÍÊÇÓÃÀ´·ÖÎöÃüÁîÐвÎÊýµÄº¯Êý¡£
ÔÚ¼ÌÐøÌÖÂÛgetopt ֮ǰ£¬ÏÈÒªÃ÷È·Á½¸ö¸ÅÄѡÏî(option) ºÍ Ñ¡Ïî²ÎÊý(argument)¡£
ÔÚÉÏÃæµÄÀý×ÓÖУ¬-g ÖÐµÄ g£¬-o ÖÐµÄ o »¹ÓÐ -lm ÖÐµÄ l ¾ÍÊÇÑ¡Ï¶ø -lm ÖÐµÄ m ¾ÍÊÇ l µÄÑ¡Ïî²ÎÊý£¬-o foo ÖÐµÄ foo ¾ÍÊÇ o µÄÑ¡Ïî²ÎÊý¡£Òò´Ë£¬ÎÒÃÇÖªµÀÁËÑ¡ÏîÓÐÁ½ÖÖ£¬Ò»ÖÖÊÇ´øÑ¡Ïî²ÎÊýµÄ£¬ÁíÒ»ÖÐÊDz»´øÑ¡Ïî²ÎÊýµÄ¡£
ÏÂÃæÎÒÃǾͿÉÒÔ¼ÌÐøÌÖÂÛ getopt() ÁË¡£
Ê×ÏÈÊǺ¯ÊýÉùÃ÷£º
#include
extern char *optarg;
extern int optind;
extern int optopt;
extern int opterr;
extern int optreset;
int getopt(int argc, char * const *argv, const char *optstring);
getopt()ÿµ÷ÓÃÒ»´Î·µ»ØÒ»¸öÑ¡Ïî¡£
argc ºÍ argv ºÜÏÔÈ»¾ÍÊÇ main º¯ÊýµÄÁ½¸ö²ÎÊý¡£
×Ö·û´® optstring ¿ÉÒÔ°üº¬ÏÂÁÐÔªËØ£ºµ¥¸ö×Ö·û£¬×Ö·ûºóÃæ½ÓÒ»¸öðºÅ˵Ã÷ºóÃæ¸úËæÒ»¸öÑ¡Ïî²ÎÊý£¬×Ö·ûºóÃæ½ÓÁ½¸öðºÅ˵Ã÷ºóÃæ¸úËæÒ»¸ö¿ÉÓпÉÎÞµÄÑ¡Ïî²ÎÊý¡£ÀýÈ磬һ¸öÑ¡Ïî×Ö·û "x" ±íʾѡÏî "-x" £¬Ñ¡Ïî×Ö·û "x:" ±íʾѡÏîºÍÆä²ÎÊý "-x argument"£¬Ñ¡Ïî×Ö·û "x::" ±íʾѡÏî x µÄ²ÎÊýÊÇ¿ÉÑ¡µÄ(¡°::¡± ÊÇ GNU Ôö¼ÓµÄ£¬²»Ò»¶¨ÔÚËùÓеÄUNIX ϵͳ϶¼¿ÉÒÔʹÓÃ)¡£
getopt()µÄ·µ»Øºó£¬Èç¹ûÓÐÑ¡Ïî²ÎÊýµÄ»° optarg Ö¸ÏòÑ¡Ïî²ÎÊý£¬²¢ÇÒ±äÁ¿ optind °üº¬ÏÂÒ»¸ö argv ²ÎÊý×÷Ϊ¶Ô getopt() ÏÂÒ»´Îµ÷ÓõÄË÷Òý¡£±äÁ¿ optopt ±£´æ×îºóÒ»¸öÓÉ getopt() ·µ»ØµÄÒÑÖªµÄÑ¡Ïî¡£
µ±²ÎÊýÁÐÒѾµ½½áβʱgetopt()º¯Êý·µ»Ø-1£¬µ±Óöµ½Ò»¸öδ֪µÄÑ¡Ïîʱ getopt ·µ»Ø'?'¡£²ÎÊýÁÐÖÐÑ¡ÏîµÄ½âÊÍ¿ÉÄܻᱻ'--'È¡Ïû£¬ÓÉÓÚËüÒýÆð getopt()¸ø²ÎÊý´¦Àí·¢ËͽáÊøÐźŲ¢·µ»Ø-1¡£
±ÈÈ磺
./getopt -a -- -c -b foo
getopt µÄÔ´´úÂëÔÚÏÂÃ棬getopt ½«Ö»»á½âÊ͵½ -a¡£
ÏÂÃæÊÇÒ»¸ö×î¼òµ¥µÄÀý×Ó£º
/* getopt.c */
#include
#include
int main(int argc, char * argv[])
{
int aflag=0, bflag=0, cflag=0;
int ch;
// opterr = 0;
while ((ch = getopt(argc, argv, "ab:c")) != -1)
{
printf("optind: %d\n", optind);
switch (ch) {
case 'a':
printf("HAVE option: -a");
aflag = 1;
break;
case 'b':
printf("HAVE option: -b");
bflag = 1;
printf("The argument of -b is %s\n", optarg);
break;
case 'c':
printf("HAVE option: -c");
cflag = 1;
break;
case '?':
printf("Unknown option: %c\n",(char)optopt);
break;
}
}
}
³ÌÐòºÜ¼òµ¥£¬Ôڴ˾Ͳ»×÷½âÊÍÁË¡£
±äÁ¿opterrºÍoptind¶¼±»³õʼ»¯Îª1¡£Èç¹ûÏëÒªÂÔÈ¥ÃüÁîÐеÄÇ°¼¸¸ö²ÎÊý£¬¿ÉÒÔÔÚµ÷ÓÃgetopt()Ç°½«optindÉè³ÉÆäËûÖµ¡£
Èç¹û²»Ï£Íûgetopt()Êä³ö³ö´íÐÅÏ¢£¬½«È«Óò±äÁ¿ opterr ÉèΪ 0 ¼´¿É¡£
GNU Linux ÖÐ¶Ô getopt ×öÁËÏàÓ¦µÄÀ©Õ¹£¬ÌṩÁ˶Գ¤²ÎÊý£¬ÀýÈç ¡°--help¡± µÄÖ§³Ö¡£Ö÷ÒªÊÇÌṩÁË getopt_long º¯Êý£¬ÏÖÔÚÎÒ»¹Ã»ÓÐÍêȫѧ»á£¬µÈѧ»áÁ˺óÔÙÀ´Ð©Ò»Æª¶ÌÎĽéÉÜËü¡£