getopt( )和 getopt_long( )
生活随笔
收集整理的這篇文章主要介紹了
getopt( )和 getopt_long( )
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
有關(guān)系統(tǒng)調(diào)用getopt:
聲明:
???????? #include <unistd.h>
???????? int getopt(int argc, char *const argv[], const char *optstring);
???????? extern char *optarg;
???????? extern int optind, opterr, optopt;
使用方法:在while循環(huán)中反復(fù)調(diào)用,直到它返回-1。每當(dāng)找到一個有效的選項字母,它就返回這個字母。如果選項有參數(shù),就設(shè)置optarg指向這個參數(shù)。
當(dāng)程序運行時,getopt()函數(shù)會設(shè)置控制錯誤處理的幾個變量:
char *optarg ──如果選項接受參數(shù)的話,那么optarg就是選項參數(shù)。
int optind──argv的當(dāng)前索引,當(dāng)while循環(huán)結(jié)束的時候,剩下的操作數(shù)在argv[optind]到argv[argc-1]中能找到。
int opterr──當(dāng)這個變量非零(默認(rèn)非零)的時候,getopt()函數(shù)為"無效選項”和“缺少選項參數(shù)”這兩種錯誤情況輸出它自己的錯誤消息。可以在調(diào)用getopt()之前設(shè)置opterr為0,強(qiáng)制getopt()在發(fā)現(xiàn)錯誤時不輸出任何消息。
聲明:
???????? #include <unistd.h>
???????? int getopt(int argc, char *const argv[], const char *optstring);
???????? extern char *optarg;
???????? extern int optind, opterr, optopt;
使用方法:在while循環(huán)中反復(fù)調(diào)用,直到它返回-1。每當(dāng)找到一個有效的選項字母,它就返回這個字母。如果選項有參數(shù),就設(shè)置optarg指向這個參數(shù)。
當(dāng)程序運行時,getopt()函數(shù)會設(shè)置控制錯誤處理的幾個變量:
char *optarg ──如果選項接受參數(shù)的話,那么optarg就是選項參數(shù)。
int optind──argv的當(dāng)前索引,當(dāng)while循環(huán)結(jié)束的時候,剩下的操作數(shù)在argv[optind]到argv[argc-1]中能找到。
int opterr──當(dāng)這個變量非零(默認(rèn)非零)的時候,getopt()函數(shù)為"無效選項”和“缺少選項參數(shù)”這兩種錯誤情況輸出它自己的錯誤消息。可以在調(diào)用getopt()之前設(shè)置opterr為0,強(qiáng)制getopt()在發(fā)現(xiàn)錯誤時不輸出任何消息。
int optopt──當(dāng)發(fā)現(xiàn)無效選項的進(jìn)修,getopt()函數(shù)或者返回'?'字符,或者返回字符':'字符,并且optopt包含了所發(fā)現(xiàn)的無效選項字符。
?
范例 #include<stdio.h>
#include<unistd.h> int main(int argc,char **argv) { int ch; opterr = 0; while((ch = getopt(argc,argv,”a:bcde”))!= -1) switch(ch) { case ‘a(chǎn)’: printf(“option a:’%s’\n”,optarg); break; case ‘b’: printf(“option b :b\n”); break; default: printf(“other option :%c\n”,ch); } printf(“optopt +%c\n”,optopt); } 執(zhí)行 $./getopt –b option b:b 執(zhí)行 $./getopt –c other option:c 執(zhí)行 $./getopt –a other option :? 執(zhí)行 $./getopt –a12345 option a:’12345’轉(zhuǎn)載于:https://www.cnblogs.com/ancient/p/3202157.html
總結(jié)
以上是生活随笔為你收集整理的getopt( )和 getopt_long( )的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 鲜为人知的C++ IO fstream
- 下一篇: 单链表 操作的18种算法