Cod sursa(job #1359628)

Utilizator McVxCretu Alexandru McVx Data 25 februarie 2015 00:26:37
Problema Convertor Scor 20
Compilator c Status done
Runda rosedu_cdl_2015 Marime 1.67 kb
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void parseObject(char *object);
void parsePair(char *pair);

int printKeys;
FILE *out;

int main(void)
{
	FILE *jsonFile = fopen("convertor.in", "r");
	char *jsonString = calloc(12048, sizeof(char));
	int l = 0;
	char c, *cpy = calloc(12048, 1);

	out = fopen("convertor.out", "w");

	printKeys = 1;

	while (c = fgetc(jsonFile))
	{
		if (c == EOF)
		{
			break;
		}

		jsonString[l++] = c;
	}

	char *p = strtok(jsonString, "}");
	while (p)
	{
		if (strlen(p) > 2)
		{
			if (printKeys == 1)
			{
				strcpy(cpy, p);
				parseObject(cpy);
				fprintf(out, "\n");
			}
			parseObject(p);
			fprintf(out, "\n");
		}
		p = strtok(NULL, "}");
	}

	fclose(jsonFile);

	return 0;
}

void parseObject(char *object)
{
	char *x = calloc(11024, sizeof(char));
	char *p = strchr(object, ',');
	while (p)
	{
		*p = 0;
		strcpy(x, object);
		if (strlen(x) > 2)
		{
			parsePair(x);
		}
		object = p + 1;
		p = strchr(object, ',');
	}
	strcpy(x, object);
	if (strlen(x) > 0)
	{
		parsePair(x);
	}
	object = p + 1;

	if (printKeys)
	{
		printKeys = 0;
	}
}

void parsePair(char *pair)
{
	char *key = calloc(11512, sizeof(char));
	char *value = calloc(11512, sizeof(char));
	char *c = "  {[(,:\"\n\0\t";

	int l = 0;
	char *p = strchr(pair, '"');
	p++;
	while (*p != '"')
	{
		key[l++] = *p;
		p++;
	}
	key[l] = 0;




	l = 0;
	p = strchr(pair, ':');
	p++;
	int v = 0;
	while (*p != 0)
	{
		if (v == 0 && strchr(c, *p))
		{
			p++;
			continue;
		}
		else
		{
			v = 1;
		}

		if (v == 1 && *p == '"')
		{
			break;
		}

		value[l++] = *p;
		p++;
	}
	value[l] = 0;

	if (printKeys == 1)
	{
		fprintf(out, "%s,", key);
	}
	else
	{
		fprintf(out, "%s,", value);
	}
}