linux系統呼叫getopt
函式說明 getopt()用來分析命令列引數。引數argc和argv分別代表引數個數和內容,跟main()函式的命令列引數是一樣的。
引數 optstring為選項字串, 告知 getopt()可以處理哪個選項以及哪個選項需要引數,如果選項字串裡的字母后接著冒號“:”,則表示還有相關的引數,全域變數optarg 即會指向此額外引數。如果在處理期間遇到了不符合optstring指定的其他選項getopt()將顯示一個錯誤訊息,並將全域變數optarg設為“?”字元,如果不希望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;
getopt() 所設定的全域性變數包括:
optarg——指向當前選項引數(如果有)的指標。 optind——再次呼叫 getopt() 時的下一個 argv 指標的索引。 optopt——最後一個未知選項。
optstring中的指定的內容的意義(例如getopt(argc, argv, "ab:c:de::");)
1.單個字元,表示選項,(如上例中的abcde各為一個選項)
2.單個字元後接一個冒號:表示該選項後必須跟一個引數。引數緊跟在選項後或者以空格隔開。該引數的指標賦給optarg。(如上例中的b:c:)
3 單個字元後跟兩個冒號,表示該選項後可以跟一個引數,也可以不跟。如果跟一個引數,引數必須緊跟在選項後不能以空格隔開。該引數的指標賦給optarg。(如上例中的e::,如果沒有跟引數,則optarg = NULL)
示例:
#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 : printf("xxxtest");
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);
}
return 0;
}
#include<unistd.h>
int main(int argc, char *argv[])
{
int ch;
opterr = 0;
while((ch = getopt(argc,argv,"a:bcde"))!= -1)
{
switch(ch)
{
case : printf("xxxtest");
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);
}
return 0;
}
執行 $./getopt –b
option b:b
執行 $./getopt –c
other option:c
執行 $./getopt –a
other option :?
執行 $./getopt –a12345
option a:’12345’
轉自getopt百度百科相關文章
- linux系統getopt函式詳解Linux函式
- Linux系統呼叫原理Linux
- Linux系統呼叫列表Linux
- Linux-getoptLinux
- linux getopt 命令Linux
- linux 中getopt和getopt_long 用法解析Linux
- Linux系統呼叫過程分析Linux
- Linux系統呼叫講義(轉)Linux
- Linux作業系統分析 | 深入理解系統呼叫Linux作業系統
- Linux選項解釋-getopt和getopt_long函式Linux函式
- Linux系統呼叫機制淺析Linux
- linux之getopt 函式(轉)Linux函式
- 線上環境 Linux 系統呼叫追蹤Linux
- Linux 下系統呼叫的三種方法Linux
- linux系統呼叫第一篇Linux
- getopt和getopt_long
- getopt與getopt_long
- 在 Linux 上用 strace 來理解系統呼叫Linux
- linux軟中段和系統呼叫深入研究Linux
- 為Linux-3.10.1核心新增系統呼叫Linux
- Linux核心模組程式設計--系統呼叫(轉)Linux程式設計
- 在Linux中新增新的系統呼叫(轉)Linux
- Linux下getopt函式的使用Linux函式
- linux下getopt函式的用法Linux函式
- Linux系統程式設計(七)檔案許可權系統呼叫Linux程式設計
- dup()系統呼叫
- Linux系統呼叫詳解(實現機制分析)Linux
- getopt_long函式基本用法-linux函式Linux
- 系統呼叫篇——SSDT
- 學習筆記 作業系統Linux-Ubuntu 之初次新增系統呼叫筆記作業系統LinuxUbuntu
- getopt for windowsWindows
- 使用 Ptrace 去攔截和模擬 Linux 系統呼叫Linux
- x64架構下Linux系統函式呼叫架構Linux函式
- 【linux】系統呼叫版串列埠分析&原始碼實戰Linux串列埠原始碼
- 如何利用Ptrace攔截和模擬Linux系統呼叫Linux
- Linux核心分析--系統呼叫實現程式碼分析(轉)Linux
- Linux下getopt()函式的簡單使用Linux函式
- MIPS Linux 下新增系統呼叫,以Linux kernel 2.6.18為例.Linux