Cod sursa(job #1346147)

Utilizator horia.zegheruZegheru Horia-Alexandru horia.zegheru Data 18 februarie 2015 02:27:35
Problema Convertor Scor 100
Compilator c Status done
Runda rosedu_cdl_2015 Marime 1.91 kb
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>

int main()
{
	FILE *f = fopen("convertor.in", "r");
	FILE *g = fopen("convertor.out", "w");

	fseek(f, 0, SEEK_END);
	int size = ftell(f), i;
	fseek(f, 0, SEEK_SET);

	char *text = (char *)malloc(sizeof(char) * (size + 1));
	fread(text, size, sizeof(char), f);

	// the current character is not : or "
	int rule = 1;
	// we need to count the quotation marks and check if : was met
	int quote_nr = 0, colonmark = 0;

	for (i = 0; i < size; i++)
	{
		// get headers from file (they can be found until the first } )
		if (text[i] != '}')
		{

			if (text[i] == ':')
				colonmark = 1; // we have just read :
			else if (text[i] == ',')
				colonmark = 0;

			if (text[i] == '\"')
			{
				quote_nr++;
				rule = 0;
			}
			else
				rule = 1;

			// check if we are before : and between quotation marks and text[i] != "
				if (quote_nr % 2 == 1 && colonmark == 0 && rule == 1)
					fprintf (g, "%c", text[i]);
				else
					if (text[i] == ',')
						fprintf(g, ",");
		}
		else
		{
			fprintf(g, ",");
			break;
		}
	}

	// get the values
	fseek(f, 0, SEEK_SET);
	colonmark = 0;
	int spaces = 1;

	for (i = 0; i < size; i++)
	{
		if (text[i] == '\"')
			quote_nr++;
		if (quote_nr % 2 == 0)
			spaces = 0;
		else spaces = 1;

		// we do not want to print text[i] if it is : or "
		if (text[i] == ':' || text[i] == '\"')
			rule = 0;
		else
			rule = 1;

		// we will print only if between : and , or }
		// ( } because for the last value there is no , )
		if (text[i] == ':')
			colonmark = 1;
		else if (text[i] == ',' || text[i] == '}')
			colonmark = 0;

		//test if after : and text[i] != " and print spaces only between ""
		if ((colonmark == 1 && rule == 1 && spaces == 1) || isdigit(text[i]))
				fprintf(g, "%c", text[i]);
			else
				if (text[i] == ',')
					fprintf(g, ",");
				else
					if (text[i] == '{')
						fprintf (g, "\n");
	}
	fprintf (g, ",\n");

	return 0;
}