2014年3月16日日曜日

開発環境

Head First C ―頭とからだで覚えるCの基本(David Griffiths (著)、Dawn Griffiths (著) 中田 秀基(監訳)(翻訳)、木下 哲也 (翻訳)、オライリージャパン)の3章(小さなツールの作成)、エクササイズ(p.115)を解いてみる。

その他参考書籍

エクササイズ(p.115)

コード(BBEdit, Emacs)

geo2json.c

#include <stdio.h>

int main(int argc, char *argv[])
{
  float latitude;
  float longitude;
  char info[80];
  int started = 0;

  puts("data=[");
  while (scanf("%f,%f,%79[^\n]", &latitude, &longitude, info) == 3) {
    if (started)
      printf(",\n");
    else
      started = 1;
    if (latitude < -90 || latitude > 90) {
      printf("invalid lantitude: %f\n", latitude);
      return (2);
    }
    if (longitude < -180 || longitude > 180) {
      printf("invalid longitude: %f\n", longitude);
      return (2);
    }
    printf("{latitude: %f, longitude: %f, info: '%s'}",
           latitude, longitude, info);
  }
  puts("\n]");
  return (0);
}

Makefile

all: geo2json

geo2json: geo2json.c
 cc -g -o geo2json geo2json.c

clean:
 rm geo2json

入出力結果(Terminal)

$ make && ./geo2json < gpsdata115.csv > output115.json
cc -g -o geo2json geo2json.c
$ cat gpsdata115.csv
42.363400,-71.098465,Speed = 21
42.363327,-71.097588,Speed = 23
42.363255,-71.096710,Speed = 17
$ cat output115.json 
data=[
{latitude: 42.363400, longitude: -71.098465, info: 'Speed = 21'},
{latitude: 42.363327, longitude: -71.097588, info: 'Speed = 23'},
{latitude: 42.363255, longitude: -71.096710, info: 'Speed = 17'}
]
$ ./geo2json < gpsdata115_1.csv > output115_1.json
$ cat gpsdata115_1.csv 
42.363400,-71.098465,Speed = 21
42.363327,-71.097588,Speed = 23
-91, 10,Speed = 10
42.363255,-71.096710,Speed = 17
$ cat output115_1.json 
data=[
{latitude: 42.363400, longitude: -71.098465, info: 'Speed = 21'},
{latitude: 42.363327, longitude: -71.097588, info: 'Speed = 23'},
invalid lantitude: -91.000000
$ echo $?
2
$ ./geo2json < gpsdata115_2.csv > output115_2.json
$ cat gpsdata115_2.csv
42.363400,-71.098465,Speed = 21
42.363327,-180.097588,Speed = 23
42.363255,-71.096710,Speed = 17
$ cat output115_2.json 
data=[
{latitude: 42.363400, longitude: -71.098465, info: 'Speed = 21'},
invalid longitude: -180.097595
$ echo $?
2
$

0 コメント:

コメントを投稿