Cod sursa(job #1355752)

Utilizator maria_anca.balutoiuBalutoiu Maria Anca maria_anca.balutoiu Data 22 februarie 2015 22:41:42
Problema Convertor Scor 0
Compilator c Status done
Runda rosedu_cdl_2015 Marime 2.43 kb
#include <stdio.h>
#include <string.h>

int main()
{
	FILE *json, *csv;
	char c, s[1000], aux = 'a', auxs[1000];
	int i = 0, k = 1, t = 0, n;
	
	json = fopen("convertor.in", "r");
	csv = fopen("convertor.out", "w");

	if (!json)
	{
		fprintf(stderr, "Eroare! Nu am putut deschide fisierul JSON\n");
		return 0;
	}

	if (!csv)
	{
		fprintf(stderr, "Eroare! Nu am putut deschide fisierul CSV\n");
		return 0;
	}

	c = fgetc(json);
	
	while (c != '\"' && c != EOF)
		c = fgetc(json);

	while (c == '\"' && c != EOF)
		c = fgetc(json);

	while (c != '}' && c != EOF)
	{
		while (c != '\"' && c != EOF && c != '}' && c != ':')
		{
			if ((aux < 'a' || aux > 'z' || aux < 'A' || aux > 'Z' || aux < '0' || aux > '9') && c != '\n' && c != ' ')
			{
				s[i] = c;
				i++;
			}
			else
				if ((aux >= 'a' && aux <= 'z') || (aux >= 'A' && aux <= 'Z') || (aux >= '0' && aux <= '9'))
				{
					s[i] = c;
					i++;
				}

			aux = c;
			c = fgetc(json);
		}

		if (c == '}')
			break;

		c = fgetc(json);
		while (c == ' ')
			c = fgetc(json);
		if (c == ':')
			while (c != ',' && c != '}' && c != EOF)
				c = fgetc(json);
		if (c == ',')
			k++;
	}

	s[i] = ',';
	s[i+1] = '\n';

	fputs(s, csv);

	fclose(json);

	json = fopen("convertor.in", "r");

	i = 0;
	s[i] = '\0';
	
	c = fgetc(json);
	
	while (c != '{' && c != EOF)
		c = fgetc(json);

	while (c != EOF)
	{
		while (c == ' ' && c != EOF)
		{
			aux = c;
			c = fgetc(json);
		}
		
		while (c != ':' && c != EOF && c != '}')
			{
				aux = c;
				c = fgetc(json);
			}

		aux = c;
		c = fgetc(json);
		
		while ((c == ' ' || c == '\n' || c == '\"') && c != EOF && c != '}')
		{
			aux = c;
			c = fgetc(json);
		}

		while ((c != '\"' && aux != ',' && c !='\n' && c != ']' && c != '}') && c != EOF)
		{
			if (c != ',')
			{
				s[i] = c;
				i++;
			}
			else
				if (s[i-1] != ',')
				{
					s[i] = c;
					i++;
				}

			aux = c;
			c = fgetc(json);
		}

		if (c == '\"')
		{
			if (s[i-1] != ',')
			{	
				s[i] = ',';
				i++;
			}
		}
	}

	s[i] = ',';
	s[i+1] = '\n';
	s[i+2] = '\0';

	n = i + 2;

	for (i = 0; i < n - 3; i++)
		if (s[i] == ',' && s[i+2] == ',')
			strcpy (s + i + 2, s + i + 3);

	if (s[n-3] == ',' && s[n-2] == ',')
	{
		s[n-2] = '\n';
		s[n-1] = '\0';
		n--;
	} 

	auxs[0] = '\0';

	for (i = 0; i < n; i++)
		if (s[i] == ',')
		{
			t++;
			if (t == k)
			{ 
				strcpy (aux, s + i + 1);
				s[i+1] = '\n';
				strcpy (s + i + 2, auxs);
				t = 0;
			}
		}

	fputs(s, csv);

	fclose(json);
	fclose(csv);
	return 0;
}