#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<ctype.h>
#define OK 0
#define CCHAR -2 /* control char */
#define MAX_KEY 50
/* usual filesystem block size is 4 KB
* so a read of 4 KB should minimize the time
* spent on IO.
* */
#define BLOCK_SIZE 4096
#define check(temp_string, orig, in) if(*temp_string == '\0') { \
temp_string = orig; \
fgets(temp_string, BLOCK_SIZE, in);\
if(feof(in)) break; \
}
int skip_to_char(char **str, char *orig, char c, char ctrl, FILE *fp) {
while(**str != c) {
check(*str, orig, fp);
if(**str == c) {
return OK;
}
if(**str == ctrl) {
return CCHAR;
}
++ *str;
}
return OK;
}
int main() {
FILE *in, *out;
in = fopen("convertor.in", "rt");
out = fopen("convertor.out", "wt");
char *string = malloc(BLOCK_SIZE * sizeof(char));
short number_of_keys = 0;
char *temp_string = string;
fgets(temp_string, BLOCK_SIZE, in);
/* read labels*/
while(skip_to_char(&temp_string, string, '"', '}', in) == OK) {
++ temp_string; /* skip " char */
check(temp_string, string, in);
while(*temp_string != '"') {
fprintf(out, "%c", *temp_string);
++ temp_string;
check(temp_string, string, in);
}
fprintf(out, ",");
++ number_of_keys;
++ temp_string; /* skip the last " */
if(skip_to_char(&temp_string, string, ',', '}', in) == CCHAR) {
break;
}
}
fprintf(out, "\n");
fseek(in, 0, SEEK_SET);
temp_string = string;
fgets(temp_string, BLOCK_SIZE, in);
/* read values */
short k = 1;
while(!feof(in)) {
check(temp_string, string, in);
skip_to_char(&temp_string, string, ':', 0, in);
if(feof(in)) break;
++ temp_string;
check(temp_string, string, in);
//skip_str(&temp_string, string, " \t\n", in);
while(!isdigit(*temp_string) && !(*temp_string == '"')) {
++ temp_string;
check(temp_string, string, in);
fflush(stdout);
}
if(isdigit(*temp_string)) {
while(isdigit(*temp_string)) {
fprintf(out, "%c", *temp_string);
++ temp_string;
check(temp_string, string, in);
}
} else {
++ temp_string;
check(temp_string, string, in);
while(*temp_string != '"') {
fprintf(out, "%c", *temp_string);
++ temp_string;
check(temp_string, string, in);
}
}
if(k == number_of_keys) {
k = 1;
fprintf(out, ",\n");
} else {
++ k;
fprintf(out, ",");
}
}
free(string);
fclose(in);
fclose(out);
return 0;
}