Cod sursa(job #1359751)

Utilizator McVxCretu Alexandru McVx Data 25 februarie 2015 02:01:46
Problema Convertor Scor 100
Compilator c Status done
Runda rosedu_cdl_2015 Marime 1.64 kb
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void parseJsonObject(char *object)
{
	char *retarded = " '\"()\n ";
	char *value; int l;
	char *q, *r;
	char *p = strtok(object, ",");
	while (p)
	{
		q = strchr(p, ':');
		q++;
		while (strchr(retarded, *q))
		{
			q++;
		}

		r = q + strlen(q);
		while (strchr(retarded, *r))
		{
			r--;
		}
		r++;

		value = calloc(r - q + 1, sizeof(char));
		strncpy(value, q, r - q);
		printf("%s,", value);

		free(value);

		p = strtok(NULL, ",");
	}

	printf("\n");
}

void printKeys(char *object)
{
	char *cpy = calloc(strlen(object) + 1, sizeof(char));
	strcpy(cpy, object);

	char *key;
	char *q, *r;
	char *retarded = " '\"()\n ";
	char *p = strtok(cpy, ",");
	while (p)
	{
		q = p;
		while (strchr(retarded, *q))
		{
			q++;
		}

		r = strchr(q, '"');
		key = calloc(r - q + 1, sizeof(char));
		strncpy(key, q, r - q);

		printf("%s,", key);
		free(key);

		p = strtok(NULL, ",");
	}

	free(cpy);
	printf("\n");
}

int main(void)
{
	FILE *jsonFile = fopen("convertor.in", "r");
	freopen("convertor.out", "w", stdout);

	char c;
	char *jsonObject;
	int l;
	int o = 0;
	int pK = 0;

	while (c = fgetc(jsonFile))
	{
		if (c == EOF)
		{
			break;
		}
		
		if (c == '[' || c == ']')
		{
			continue;
		}
		else if (c == '{')
		{
			o = 1;
			l = 0;
			jsonObject = calloc(1, sizeof(char));
		}
		else if (c == '}')
		{
			o = 0;
			jsonObject[l] = 0;
			if (pK == 0)
			{
				printKeys(jsonObject);
				pK = 1;
			}
			parseJsonObject(jsonObject);
			free(jsonObject);
			jsonObject = NULL;
		}
		else if (o == 1)
		{
			jsonObject[l++] = c;
			jsonObject = realloc(jsonObject, l + 1);
		}
	}

	fclose(jsonFile);

	return 0;
}