Pagini recente » Cod sursa (job #447864) | Cod sursa (job #189202) | Cod sursa (job #2349350) | Cod sursa (job #3193597) | Cod sursa (job #1350036)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define STRING 2
#define INT 1
int main()
{
FILE* IN = fopen("convertor.in", "r");
FILE* OUT = fopen("convertor.out", "w");
char line[1024], *readBuffer, ***table;
int length, crtKey = 0, crtVal = 0, crtObj = 0, bufferCrt = 0, bufferLength = 10, bufferStep = 10;
int i, j;
short isReading = 0, isValue = 0, type = 0;
readBuffer = (char *)malloc(bufferLength * sizeof(char));
table = (char***)malloc( sizeof(char**) );//table header / keys' row
table[0] = (char**)malloc(sizeof(char*));
//start of JSON
while ( fgetc(IN) != '[' );
while( fgets(line, 1024, IN) != NULL )
{
length = strlen(line);
for( i = 0 ; i < length ; i++ )
{
if(line[i] == ']')
break;
if( !isReading )
{
switch(line[i])
{
case '{': //next object
crtObj++;
crtVal = 0;
table = (char***)realloc(table, (crtObj+1) * sizeof(char**));
table[crtObj] = (char**)malloc(sizeof(char*));
break;
case '"': //cheie
isReading = 1;
isValue = 0;
type = STRING; //cheia e de tip string
break;
case ':': //valoare
isReading = 1;
isValue = 1;
break;
default: //pentru spatii, tab-uri...
continue;
}
}
else
{
if(!type && isValue)//get value type
{
if(line[i] >= '0' && line [i] <= '9')
type = INT; //int
else if(line[i] == '"')
{
type = STRING; //string
continue; //string-ul incepe de la urmatorul caracter
}
else
continue;//salt peste caracterele dintre : si value
}
if( (type == STRING && line[i] == '"') ||
(type == INT && !(line[i] >= '0' && line [i] <= '9') ) )//sfarsitul citirii unei chei/valori
{
readBuffer[bufferCrt++] = '\0';//end of string
if(!isValue && crtObj == 1)//write the keys in table header.. array
{
table[0] = (char**)realloc( table[0], (crtKey+1) * sizeof(char*));
table[0][crtKey] = (char*)malloc( bufferCrt * sizeof(char) );
//copy the key from buffer to table
for( j=0 ; j<bufferCrt ; j++ )
table[0][crtKey][j] = readBuffer[j];
crtKey++;
}
else if(isValue)
{
table[crtObj] = (char**)realloc( table[ crtObj ], (crtVal+1) * sizeof(char*));
table[crtObj][crtVal] = (char*)malloc( bufferCrt * sizeof(char) );
//copy the value from buffer to table
for( j=0 ; j<bufferCrt ; j++)
table[crtObj][crtVal][j] = readBuffer[j];
crtVal++;
}
free(readBuffer);
bufferCrt = isReading = isValue = type = 0;
bufferLength = 10;
readBuffer = (char *) malloc (bufferLength * sizeof(char));
continue;
}
if(bufferCrt <= bufferLength)
{
bufferLength += bufferStep;
readBuffer = (char *)realloc( readBuffer, bufferLength * sizeof(char) );
}
readBuffer[bufferCrt++] = line[i];
}
}
}
for(i=0;i<=crtObj;i++)
{
for(j=0;j<crtKey;j++)
fprintf(OUT, "%s,", table[i][j]);
fprintf(OUT, "\n");
}
for(i=0;i<=crtObj;i++)
{
for(j=0;j<crtKey;j++)
free(table[i][j]);
free(table[i]);
}
free(table);
fclose(IN);
fclose(OUT);
return 0;
}