Guest User

Untitled

a guest
Oct 20th, 2018
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.75 KB | None | 0 0
  1. /*
  2. * Takes CSV data as input and converts it to json
  3. * In this case we're using earthquake data
  4. */
  5. #include <stdio.h>
  6. #include <stdlib.h>
  7. #include <errno.h>
  8.  
  9. // define the maximum amount of data
  10. #define MAX 256
  11.  
  12. // Kill the program and show an error message
  13. void die(const char *msg)
  14. {
  15. if(errno)
  16. perror(msg);
  17. else
  18. printf("%s\n", msg);
  19. exit(1);
  20. }
  21.  
  22. int main(int argc, char *argv[])
  23. {
  24. // set up the variables for our expected data
  25. char src[10];
  26. char eqid[MAX];
  27. char version[MAX];
  28. char date[MAX];
  29. float latitude;
  30. float longitude;
  31. float magnitude;
  32. float depth;
  33. int nst;
  34. char region[MAX];
  35. int started = 0;
  36.  
  37. // we'll convert the data into json wrapped inside a callback function
  38. printf("data_callback ({");
  39. printf("\"data\": [");
  40. // scan through the data we get and set our variables
  41. while(scanf(" %9[^,],%255[^,],%255[^,],\"%255[^\"]\",%f,%f,%f,%f,%d,%255[^\n]", src, eqid, version, date, &latitude, &longitude, &magnitude, &depth, &nst, region) == 10) {
  42. if(started)
  43. printf(",\n");
  44. else
  45. started = 1;
  46. // stay within latitude and longitude
  47. if((latitude < -90.0) || (latitude > 90.0)) {
  48. die("Latitude out of bounds");
  49. }
  50. else if((longitude < -180.0) || (longitude > 180.0)) {
  51. die("Longitude out of bounds");
  52. }
  53.  
  54. printf("{\"src\": \"%s\", \"eqid\": \"%s\", \"version\": \"%s\", \"date\": \"%s\", \"latitude\": %f, \"longitude\": %f, \"magnitude\": %f, \"depth\": %f, \"nst\": %d, \"region\": %s}", src, eqid, version, date, latitude, longitude, magnitude, depth, nst, region);
  55.  
  56. }
  57. // close the object and function
  58. printf("\n]})");
  59. return 0;
  60. }
Add Comment
Please, Sign In to add comment