1. 这是一个gps 数据过滤的小工具,目的是过滤到gps数据中不符合要求的数据,然后转为json 数据
需要两个小工具
bermuda.c ------> 过滤一定范围的数据
geo2json.c ------> 将gps 数据转换成json 格式
指的注意的是 需要在这两个文件的可执行文件中间建立连接管道
先看 bermuda.c 的代码
#include <stdio.h> int main() { float latitude; float longitude; char info[80]; while (scanf("%f,%f,%79[^\n]",&latitude,&longitude,info) == 3) { if (latitude > 26 && latitude < 34) { if (longitude > -76 && longitude < -64) { printf("%f,%f,%s\n",latitude,longitude,info); } } } return 0; }
再看geo2json.c 的代码
#include <stdio.h> int main() { 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.0 || latitude > 90.0) {
// stderr 是标准错误输出,一旦发生错误,不会把错误输入到标准输出的文件中,而是输出到前台 fprintf(stderr, "Invalid latitude: %f\n",latitude); return 2; } if (longitude < -180.0 || longitude > 180.0) { fprintf(stderr, "Invalid longitude: %f\n",longitude); return 2; } printf("latitude: %f, longitude : %f, info: '%s'",latitude,longitude,info); } puts("\n]"); return 0; }
使用终端 进到 这两个文件的目录下,执行命令 编译成可执行文件
gcc bermuda.c -o bermuda
gcc geo2json.c -o geo2json
然后 建立管道 传入 数据输入文件 到处到文件中outpu.json
(./bermuda | ./geo2json) <spooky.csv> output.json
输入文件 spooky.csv 的文件内容是
30.685163,-68.137207,Type=Yeti 28.304380,-74.575195,Type=UFO 29.132971,-71.136475,Type=Ship 28.343065,-62.753906,Type=Elvis 27.868217,-68.005371,Type=Goatsucker 30.496017,-73.333740,Type=Disappearance 26.224447,-71.477051,Type=UFO 29.401320,-66.027832,Type=Ship 37.879536,-69.477539,Type=Elvis 22.705256,-68.192139,Type=Elvis 27.166695,-87.484131,Type=Elvis
最终输出文件outpu.json 的内容是
data = [ latitude: 30.685163, longitude : -68.137207, info: 'Type=Yeti', latitude: 28.304380, longitude : -74.575195, info: 'Type=UFO', latitude: 29.132971, longitude : -71.136475, info: 'Type=Ship', latitude: 27.868217, longitude : -68.005371, info: 'Type=Goatsucker', latitude: 30.496017, longitude : -73.333740, info: 'Type=Disappearance', latitude: 26.224447, longitude : -71.477051, info: 'Type=UFO', latitude: 29.401320, longitude : -66.027832, info: 'Type=Ship' ]
2. 这是对文件的操作 ,读取文件中的数据,然后根据条件 把符合条件的内容导入到相应的文件中
#include <stdio.h> #include <stdlib.h> #include <string.h> int main(int argc , char *argv[]) { char line[80]; if (argc != 6) { fprintf(stderr, "你必须输入5个参数!"); } 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(file1); fclose(file2); fclose(file3); return 0; }
把spooky.csv 和 本代码放到同一目录,然后运行命令
gcc categorize.c -o categorize
编译成功后 在运行命令
./categorize Ship ship.csv Elvis elvis.csv other.csv
就会得到三个文件,分别记录着Ship Elvis 和 其他的信息,
这里使用了命令行参数的功能,用户可以根据一定的规则来动态帅选内容
必须说明的是 main 函数中的参数是很有用的