Code:number-pairs-to-array-file.c
The main use-case of this code, is to take certain SQL results and convert them to array files that can be used in the image generator.
Example of how this was used: The results of a query in Code:food1.sql were used to generate File:yields.data-float64-895x1 which was used in generating File:food-crop-production1.png.
Code
// takes pairs of numbers from stdin
// reads them as "index" and "value"
// puts them into an array
// saves the array to an output file
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <ctype.h>
#define MAXSIZE 1048576
int size=0;
char *name="out";
double default_value=NAN;
double a[MAXSIZE];
int main(int argc, char **argv) {
if (argc >= 2) { char *p=argv[1]; while (*p && (*p=='-'||*p=='_'||isalnum(*p))) p++; if (!*p) name = argv[1]; }
if (argc >= 3) default_value = atof(argv[2]);
for (int i=0; i<MAXSIZE; i++) a[i] = default_value;
while (1) {
double index, value;
if (scanf("%lf %lf", &index, &value) != 2) break;
int i = index;
if (i < 0) { printf("Index can't be negative\n"); continue; }
if (i >= MAXSIZE) { printf("Index too big, can't add it\n"); continue; }
if (i >= size) size = i+1;
a[i] = value;
}
char filename[256];
sprintf(filename, "data/%s.data-float64-%dx1", name, size);
FILE *f = fopen(filename, "w");
if (!f) { perror(filename); return 1; }
printf("Writing file: %s\n", filename);
fwrite(a, sizeof(double), size, f);
fclose(f);
return 0;
}