2015年1月27日火曜日

開発環境

Head First C ―頭とからだで覚えるCの基本(David Griffiths (著)、Dawn Griffiths (著) 中田 秀基(監訳)(翻訳)、木下 哲也 (翻訳)、オライリージャパン)の3章(小さなツールの作成: 1つのことだけをうまくやる)、ピザの一切れ(p.150)を解いてみる。

その他参考書籍

ピザの一切れ(p.150)

コード(BBEdit, Emacs)

order_pizza.c

#include <stdio.h>
#include <unistd.h>

int main(int argc, char **argv){
  char *delivery = "";
  int thick = 0;
  char ch;
  while ((ch = getopt(argc, argv, "d:t")) != EOF) {
    if (ch == 'd') delivery = optarg;
    else if (ch == 't') thick = 1;
    else {
      fprintf(stderr, "Unknown option: '%s'\n", optarg);
      return 1;
    }
  }
  argc -= optind;
  argv += optind;
  if (thick) printf("Thick crust.\n");
  if (delivery[0]) printf("To be delivered %s.\n", delivery);
  printf("Ingredients:\n");
  for (int i = 0; i < argc; i++)
    printf("%s\n", argv[i]);
}
  

入出力結果(Terminal)

$ make order_pizza
clang ...
$ ./order_pizza
Ingredients:
$ ./order_pizza -d
./order_pizza: option requires an argument -- d
Unknown option: '(null)'
$ ./order_pizza -d now
To be delivered now.
Ingredients:
$ ./order_pizza -d now -t
Thick crust.
To be delivered now.
Ingredients:
$ ./order_pizza -d now -t tomato cheese
Thick crust.
To be delivered now.
Ingredients:
tomato
cheese
$ ./order_pizza -t -d now tomato cheese
Thick crust.
To be delivered now.
Ingredients:
tomato
cheese
$ ./order_pizza -td now tomato cheese
Thick crust.
To be delivered now.
Ingredients:
tomato
cheese
$ ./order_pizza -a
./order_pizza: illegal option -- a
Unknown option: '(null)'
$

0 コメント:

コメントを投稿