$./order_pizza -d now -t Anchovies Pineapple
Output:
Thick crust.
To be delivered now.
Ingredients:
Anchovies
Pineapple
#include <stdio.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
char *delivery = "";
int thick = 0;
int count = 0;
char ch;
//"d:t"表示d選項與t選項有效,又因為":",所以d選項需要引數
while ((ch = getopt(argc, argv, "d:t")) != EOF)
switch(ch){
case 'd': //在這裡讀取"d"選項的引數
delivery = optarg; //getopt()以optarg變數指向該引數
break;
case 't':
thick = 1;
break;
default:
fprintf(stderr, "Unknow option: '%s'\n", optarg);
return 1;
}
argc -= optind; //這兩行,確保我們跳過已讀取的選項
argv += optind; //optind變數,儲存從命令列讀取的字串數,以便跳過那些選項
if(thick)
puts("Thick crust.");
if(delivery[0])
printf("To be delivered %s.\n", delivery);
puts("Ingredients:");
for (count = 0; count < argc; count++)
puts(argv[count]);
return 0;
}
沒有留言:
張貼留言