#include<stdio.h>
#include<stdlib.h>
#include<string.h>
void keys(FILE* f, FILE* g, int* keyLenght, int* keyIndex)
{
int keyFlag = 1, stringFlag = 0, currentKeyLength = 0;
char x = 0, string[100000];
string[0] = '\0';
while(x != '}'){
x = getc(f);
while(x == ' ' && !stringFlag){
x = getc(f);
}
//if a key follows
if(x == ','){
keyFlag = 1;
currentKeyLength = 0;
string[strlen(string)] = ',';
}
//if the value of a key follows
else if(x == ':'){
keyFlag = 0;
fprintf(g, ",");
keyLenght[*keyIndex] = currentKeyLength;
(*keyIndex)++;
}
//if a string begins or ends
else if(x == '"'){
if(stringFlag){
stringFlag = 0;
}
else{
stringFlag = 1;
}
}
//if x is a char
else{
if(keyFlag && stringFlag){
fprintf(g, "%c", x);
currentKeyLength++;
}
else if(!keyFlag && x != '}' && x != '\n'){
//strcat(string, &x);
int len = strlen(string);
string[len] = x;
string[len + 1] = '\0';
/*char null = NULL;
strcat(string, &null);*/
}
}
}
fprintf(g, "\n");
/*char aux = ',', null = NULL;
strcat(string, &aux);
strcat(string, &null);
fprintf(g, "%s", string);*/
int len = strlen(string);
string[len] = ',';
string[len + 1] = '\0';
fprintf(g, "%s", string);
}
void CSV(FILE* f, FILE* g, int* keyLenght, int keyIndex)
{
int valueFlag = 0, objectFlag = 0, stringFlag = 0, currentObjectKey = 0;
char x = 0, buffer[1000];
while(x != ']'){
x = getc(f);
while(x == ' ' && !stringFlag){
x = getc(f);
}
if(x == '{'){
objectFlag = 1;
currentObjectKey = 0;
}
else if(x == '}'){
objectFlag = 0;
fprintf(g, ",");
}
else if(x == '"'){
if(stringFlag){
stringFlag = 0;
}
else{
stringFlag = 1;
if(!valueFlag){
if(!fread(buffer, sizeof(char), keyLenght[currentObjectKey], f)){
printf("Eroare");
}
}
}
}
else if(x == ':'){
valueFlag = 1;
}
else if(x == ','){
valueFlag = 0;
currentObjectKey++;
if(objectFlag){
fprintf(g, ",");
}
else{
fprintf(g, "\n");
}
}
else if(x == ']'){
objectFlag = 0;
valueFlag = 0;
}
else{
if(valueFlag && stringFlag && x > 0 && x != '\n'){
fprintf(g, "%c", x);
}
else if(valueFlag && x != ' ' && x > 0 && x != '\n'){
fprintf(g, "%c", x);
}
}
}
}
int main()
{
//open the files
FILE* f = fopen("convertor.in", "r");
FILE* g = fopen("convertor.out", "w");
//get the keys
int keyLenght[10100], keyIndex = 0;
//keyLenght = (int*)malloc(200 * sizeof(int));
keys(f, g, keyLenght, &keyIndex);
//start getting the objects and teir values
CSV(f, g, keyLenght, keyIndex);
//close the files
fclose(f);
fclose(g);
//free the memory
//free(keyLenght);
return 0;
}