Cod sursa(job #1346132)

Utilizator horia.zegheruZegheru Horia-Alexandru horia.zegheru Data 18 februarie 2015 01:33:01
Problema Convertor Scor 70
Compilator c Status done
Runda rosedu_cdl_2015 Marime 1.74 kb
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

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

	char curr;
	// 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;

	while (fscanf(f, "%c", &curr) != EOF)
	{
		// get headers from file (they can be found until the first } )
		if (curr != '}')
		{

			if (curr == ':')
				colonmark = 1; // we have just read :
			else if (curr == ',')
				colonmark = 0;

			if (curr == '\"')
			{
				quote_nr++;
				rule = 0;
			}
			else
				rule = 1;

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

	// get the values
	f = fopen("convertor.in", "r");
	colonmark = 0;
	quote_nr = 0;
	int spaces = 1;

	while (fscanf(f, "%c", &curr) != EOF)
	{
		if (curr == '\"')
			quote_nr++;
		if (quote_nr % 2 == 0)
			spaces = 0;
		else spaces = 1;

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

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

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

	return 0;
}