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