2018年5月30日水曜日

開発環境

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

ピザの一切れ(p. 150)

Makefile

CC = cc

all: sample run

sample: sample.c
 $(CC) sample.c -o sample

run: sample
 ./sample

コード

#include <stdbool.h>
#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) {
    switch (ch) {
    case 'd':
      delivery = optarg;
      break;
    case 't':
      thick = true;
      break;
    default:
      fprintf(stderr, "Unknown option: '%s'\n", optarg);
      return 1;
    }
  }
  argc -= optind;
  argv += optind;

  if (thick) {
    puts("Thick crust.");
  }
  if (delivery[0]) {
    printf("To be delivered %s.\n", delivery);
  }

  puts("Ingredients:");
  for (int count = 0; count < argc; count++) {
    puts(argv[count]);
  }
}

入出力結果(Terminal)

$ make
cc sample.c -o sample
./sample
Ingredients:
$ ./sample -d
./sample: option requires an argument -- d
Unknown option: '(null)'
$ ./sample  -d Delivery
To be delivered Delivery.
Ingredients:
$ ./sample -td Delivery
Thick crust.
To be delivered Delivery.
Ingredients:
$ ./sample i1
Ingredients:
i1
$ ./sample i1 i2
Ingredients:
i1
i2
$ ./sample -td Delivery i1 i2
Thick crust.
To be delivered Delivery.
Ingredients:
i1
i2
$ 

0 コメント:

コメントを投稿