C - 小さなツール - 1つのことだけをうまくやる - コマンドライン引数
Head First C ―頭とからだで覚えるCの基本、 David Griffiths(著)、 Dawn Griffiths(著)、 中田 秀基(監修)、 木下 哲也(翻訳)、 O’Reilly Media)の3章(小さなツール - 1つのことだけをうまくやる)、p.142(コードマドネット)の解答を求めてみる。
Makefile
all: categorize spooky.csv
./categorize mermaid mermaid.csv Elvis elvises.csv the_rest.csv
categorize: categorize.c
cc categorize.c -o categorize
コード
categorize.c
#include <stdio.h>
#include <string.h>
int main(int argc, char const *argv[])
{
char line[80];
if (argc != 6)
{
fprintf(stderr, "5つの引数を指定してください。\n");
return 1;
}
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);
}
CSVファイル
spooky.csv
42.363327,-71.097588,Speed = 23,Type="UFO"
42.363182,-71.095833,Speed = 22,Type="UFO"
42.362965,-71.093201,Speed = 18,Type="UFO"
42.362747,-71.090569,Speed = 23,Type="UFO"
42.362602,-71.088814,Speed = 19,Type="UFO"
42.362675,-71.089691,Speed = 14,Type="Elvis"
42.363400,-71.098465,Speed = 21,Type="Mermaid"
42.363255,-71.096710,Speed = 17,Type="Disappearance"
42.363110,-71.094955,Speed = 14,Type="Goatsucker"
42.363037,-71.094078,Speed = 16,Type="Disappearance"
42.362892,-71.092323,Speed = 22,Type="Giant octopus"
42.362820,-71.091446,Speed = 17,Type="Disappearance"
42.362530,-71.087936,Speed = 16,Type="Disappearance"
42.362457,-71.087059,Speed = 16,Type="Disappearance"
42.362385,-71.086182,Speed = 21,Type="Yeti"
CSVファイル
mermaid.csv
CSVファイル
elvises.csv
42.362675,-71.089691,Speed = 14,Type="Elvis"
the_rest.csv
42.363327,-71.097588,Speed = 23,Type="UFO"
42.363182,-71.095833,Speed = 22,Type="UFO"
42.362965,-71.093201,Speed = 18,Type="UFO"
42.362747,-71.090569,Speed = 23,Type="UFO"
42.362602,-71.088814,Speed = 19,Type="UFO"
42.363400,-71.098465,Speed = 21,Type="Mermaid"
42.363255,-71.096710,Speed = 17,Type="Disappearance"
42.363110,-71.094955,Speed = 14,Type="Goatsucker"
42.363037,-71.094078,Speed = 16,Type="Disappearance"
42.362892,-71.092323,Speed = 22,Type="Giant octopus"
42.362820,-71.091446,Speed = 17,Type="Disappearance"
42.362530,-71.087936,Speed = 16,Type="Disappearance"
42.362457,-71.087059,Speed = 16,Type="Disappearance"
42.362385,-71.086182,Speed = 21,Type="Yeti"
入出力結果(Terminal, Zsh)
% make
cc categorize.c -o categorize
./categorize mermaid mermaid.csv Elvis elvises.csv the_rest.csv
%