2018年3月26日月曜日

開発環境

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

コードマグネット(p. 143)

#include <stdio.h>
#include <string.h>

int main(int argc, char *argv[]) {
  if (argc != 6) {
    fprintf(stderr, "5つの引数を指定してください\n");
    return 1;
  }
  char line[80];
  FILE *in = fopen("spooky.csv", "r");
  FILE *file1 = fopen(argv[2], "w");
  FILE *file2 = fopen(argv[4], "w");
  FILE *file3 = fopen(argv[5], "w");
  
  while (fscanf(in, "%79[^\n]\n", line) == 1) {
    if (strstr(line, argv[1])) {
      fprintf(file1, "%s\n", line);
    } else if (strstr(line, argv[3])) {
      fprintf(file2, "%s\n", line);
    } else {
      fprintf(file3, "%s\n", line);
    }
  }
  fclose(in);
  fclose(file1);
  fclose(file2);
  fclose(file3);
}

入出力結果(Terminal)

$ cc sample.c -o sample
$ ./sample 
5つの引数を指定してください
$ ./sample mermaid
5つの引数を指定してください
$ ./sample  Mermaid mermaid.csv Elvis elvises.csv the_rest.csv
$ cat mermaid.csv 
 42.363400,-71.098465,Speed = 21,Type="Mermaid"
$ cat elvises.csv 
42.362675,-71.089691,Speed = 14,Type="Elvis"
$ cat the_rest.csv 
42.363327,-71.097588,Speed = 23,Type="UFO"
42.363255,-71.096710,Speed = 17,Type="Disappearance"
42.363182,-71.095833,Speed = 22,Type="UFO"
42.363110,-71.094955,Speed = 14,Type="Goatsucker"
42.363037,-71.094078,Speed = 16,Type="Disappearance"
42.362965,-71.093201,Speed = 18,Type="UFO"
42.362892,-71.092323,Speed = 22,Type="Giant octopus"
42.362820,-71.091446,Speed = 17,Type="Disappearance"
42.362747,-71.090569,Speed = 23,Type="UFO"
42.362602,-71.088814,Speed = 19,Type="UFO"
42.362530,-71.087936,Speed = 16,Type="Disappearance"
42.362457,-71.087059,Speed = 16,Type="Disappearance"
42.362385,-71.086182,Speed = 21,Type="Yeti"
$ cat spooky.csv 
 42.363400,-71.098465,Speed = 21,Type="Mermaid"
 42.363327,-71.097588,Speed = 23,Type="UFO"
 42.363255,-71.096710,Speed = 17,Type="Disappearance"
 42.363182,-71.095833,Speed = 22,Type="UFO"
 42.363110,-71.094955,Speed = 14,Type="Goatsucker"
 42.363037,-71.094078,Speed = 16,Type="Disappearance"
 42.362965,-71.093201,Speed = 18,Type="UFO"
 42.362892,-71.092323,Speed = 22,Type="Giant octopus"
 42.362820,-71.091446,Speed = 17,Type="Disappearance"
 42.362747,-71.090569,Speed = 23,Type="UFO"
 42.362675,-71.089691,Speed = 14,Type="Elvis"
 42.362602,-71.088814,Speed = 19,Type="UFO"
 42.362530,-71.087936,Speed = 16,Type="Disappearance"
 42.362457,-71.087059,Speed = 16,Type="Disappearance"
 42.362385,-71.086182,Speed = 21,Type="Yeti"
$

0 コメント:

コメントを投稿

関連コンテンツ