歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux基礎 >> Linux教程 >> linux常用c函數:終端控制篇(一)

linux常用c函數:終端控制篇(一)

日期:2017/2/25 10:38:45   编辑:Linux教程

  getopt(分析命令行參數)

  相關函數

  表頭文件 #include<unistd.h>

  定義函數 int getopt(int argc,char * const argv[ ],const char * optstring);

  函數說明 getopt()用來分析命令行參數。參數argc和argv是由main()傳遞的參數個數和內容。參數optstring 則代表欲處理的選項字符串。此函數會返回在argv 中下一個的選項字母,此字母會對應參數optstring 中的字母。如果選項字符串裡的字母後接著冒號“:”,則表示還有相關的參數,全域變量optarg 即會指向此額外參數。如果getopt()找不到符合的參數則會印出錯信息,並將全域變量optopt設為“?”字符,如果不希望getopt()印出錯信息,則只要將全域變量opterr設為0即可。

  返回值 如果找到符合的參數則返回此參數字母,如果參數不包含在參數optstring 的選項字母則返回“?”字符,分析結束則返回-1。

  范例 #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);

  }

Copyright © Linux教程網 All Rights Reserved