Cod sursa(job #1357994)

Utilizator theo.stoicanTheodor Stoican theo.stoican Data 24 februarie 2015 11:59:11
Problema Convertor Scor 100
Compilator c Status done
Runda rosedu_cdl_2015 Marime 2.3 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);
        fwrite ("\n", 1, 1, fout);
        //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++)
        //    fputc (p2[i], out_file);
	i = 1;
	while (p2[i] != '"') fputc (p2[i++], out_file);
        fputc (44, 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 fputc (p2[i], out_file);
		i = 1;
		while (p2[i] != '"') fputc (p2[i++], out_file);
        }
        else
        {
            len = strlen (p1);
            //consider the case where the value is an integer
            for (i = 0; i < len; i++)
                if (isdigit (p1[i]) != 0)
                    fputc (p1[i], out_file);
        }
        fputc (44, out_file);
        if (strchr (p, '}') != NULL) fwrite ("\n", 1, 1, out_file);
        p = strtok (NULL, ",");
    }
}