Cod sursa(job #1344816)

Utilizator theo.stoicanTheodor Stoican theo.stoican Data 16 februarie 2015 23:32:55
Problema Convertor Scor 100
Compilator c Status done
Runda rosedu_cdl_2015 Marime 1.85 kb
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

void extract_keys (char*, int, FILE*);
void extract_val (char*, FILE*);

int main(){
	FILE *fin, *fout;
	char *wholefile;
	int filedim;
	fin = fopen ("convertor.in", "r");
	fout = fopen("convertor.out","w");
	fseek (fin, 0, SEEK_END);
	filedim = ftell (fin);
	wholefile = (char *) calloc (filedim + 1, sizeof(char));
	fseek (fin, 0, SEEK_SET);
	if (fread (wholefile, filedim, 1, fin) == 1)
	{
		//extract the keys
		extract_keys (wholefile, filedim, fout);
		fprintf (fout,"\n");
		//extract the values
		extract_val (wholefile, fout);
	}
	free (wholefile);
	fclose(fin);
	fclose (fout);
	return 0;
}
void extract_keys (char *f, int dim, FILE *out_file)
{
	char *p, *copyp, *p2;
	int i;
	copyp = (char*) calloc (dim + 1, sizeof(char));
	p = strchr (f, '}');
	//copy the first object, in order to extract the keys
	strncpy (copyp, f, p - f);
	p2 = strchr (copyp, '"');
	while (1)
	{
		//print only the characters within the double quotes
		for (i = 1; p2[i] != '"'; i++)
			fprintf (out_file, "%c", p2[i]);
		fprintf (out_file, ",");
		p = strchr (p2, ',');
		if (p != NULL) 
			p2 = strchr (p, '"');
		else break;
	}
	free (copyp);
}
void extract_val (char *f, FILE *out_file)
{
	char *p, *p1, *p2;
	int i, len;
	p = strtok (f, ",");
	while (p != NULL)
	{
		p1 = strchr (p, ':');
		p2 = strchr (p1, '"');
		if (p2 != NULL)
		{
			len = strlen (p2);
			//consider the case where the value consists of a string
			for (i = 1; i < len; i++)
				if (p2[i] == '"') break;
				else fprintf (out_file, "%c", p2[i]);
		}
		else
		{
			len = strlen (p1);
			//consider the case where the value is an integer
			for (i = 0; i < len; i++)
				if (isdigit (p1[i]) != 0)
					fprintf (out_file, "%c", p1[i]);
		}
		fprintf (out_file, ",");
		if (strchr (p, '}') != NULL) fprintf (out_file, "\n");
		p = strtok (NULL, ",");
	}
}