Cod sursa(job #1361699)

Utilizator TwistedFaithStanescu Jean Alexandru TwistedFaith Data 25 februarie 2015 23:04:35
Problema Convertor Scor 100
Compilator c Status done
Runda rosedu_cdl_2015 Marime 2.08 kb
/* JSON to CSV */
/* Highest run time on all tests: 56ms */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>

void nfprint(char *ptr, int len);
void solveKeys(FILE * pFile);
void solveValues(FILE * pFile);

int main()
{
	/* Open input file */
	FILE *pFile = fopen("convertor.in", "rt");

	/* Redirect output from stdout to convertor.out */
	freopen("convertor.out", "wt", stdout);

	/* Check input file */
	assert(pFile != NULL);

	solveKeys(pFile);
	rewind(pFile);
	solveValues(pFile);

	fclose(pFile);
	return 0;
}

/* Prints n characters starting from the pointer */
void nfprint(char *ptr, int len)
{
	int i;

	for (i = 0; i < len; ++i)
		printf("%c", ptr[i]);

	printf(",");
}

/* FPrints the JSON keys */
void solveKeys(FILE * pFile)
{
	char *ptr1, str[1025], aux[1025];
	register short int i;
	short int len, quote = 0;

	do {
		fgets(str, 1025, pFile);
		len = strlen(str);

		for (i = 0; i < len; ++i) {
			if (*(str + i) == '"') {
				if (quote % 2 != 0) {
					strncpy(aux, ptr1 + 1, str + i - ptr1 - 1);
					aux[str + i - ptr1 - 1] = '\0';
				} else
					ptr1 = str + i;

				quote++;
			} else if (*(str + i) == ':') {
				printf("%s,", aux);

				quote = 0;
			} else if (*(str + i) == ',')
				quote = 0;
			else if (*(str + i) == '}') {
				quote = -1;
				break;
			}
		}
	}
	while (quote != -1);

	printf("\n");
}

/* Prints the JSON values */
void solveValues(FILE * pFile)
{
	char str[1025];
	register short int i;
	short int len, quote = 0, dots = 0;

	while (fgets(str, 1025, pFile) != NULL) {
		len = strlen(str);

		for (i = 0; i < len; ++i) {
			if (str[i] == ':') {
				dots = 1;
				quote = 0;
			} else if (str[i] == ',') {
				dots = 0;
				quote = 0;
			} else if (str[i] == '}') {
				dots = 0;
				printf("\n");
			} else if (str[i] == '"')
				quote = (quote + 1) % 2;

			if (dots) {
				if ((quote) && (str[i] != '"')) {
					printf("%c", str[i]);

					if (str[i + 1] == '"')
						printf(",");
				} else if ((str[i] >= 48) && (str[i] <= 57)) {
					printf("%c", str[i]);

					if (!((str[i + 1] >= 48) && (str[i + 1] <= 57)))
						printf(",");
				}
			}
		}
	}
}