Cod sursa(job #1348806)

Utilizator alexdinu712Alexandru Dinu alexdinu712 Data 19 februarie 2015 21:07:56
Problema Convertor Scor 70
Compilator c Status done
Runda rosedu_cdl_2015 Marime 2.71 kb
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <time.h>

#define _POSIX_C_SOURCE 1

#define MAX 2 * 1024 * 1024 //2MB

#define CHK(assertion) \
	if(assertion) \
		{ \
			fprintf(stderr, "error!\n"); \
			exit(1); \
		} \

char *createString(FILE *f)
{
	char *aux = malloc(MAX * sizeof(char));
	CHK(!aux);

	int i = 0;
	while((aux[i++] = fgetc(f)) != EOF);
	aux[i] = '\0';

	char *str = realloc(aux, (i + 1) * sizeof(char));
	aux = NULL;

	return str;
}

void rmChar(char *str, char c)
{
	char *src, *dest;

	// both pointers point to the first char of input
	src = dest = str;    
	// exit loop when null terminator reached
	while(*src != '\0')   
	{
		// if source is not a 'c' char and it is printable
    	if (*src != c && isprint(*src)) 
   		{
   			// copy the char at source to destination
        	*dest = *src;
        	// increment destination pointer
        	dest++;       
    	}
    	// increment source pointer
    	src++;
	}
	// terminate string with null terminator 
	*dest = '\0';          
}

void rmSpaceSel(char *str)
{
	int qt = 0;
	char *src, *dest;

	src = dest = str;   
	while(*src != '\0')   
	{
    	if (*src == '"')  
        	qt++;    

    	if((qt % 2 == 1) || 
    		(qt % 2 == 0 && (isdigit(*src) || !isblank(*src))))
    	{
    		*dest = *src;
    		dest++;
    	}
    	src++;        
	}
	*dest = '\0';          
}

void removeGarbage(char *str, char* garbage)
{
	int i; 
	int len = strlen(garbage);

	for(i = 0; i < len; i++)
	{
		rmChar(str, garbage[i]);
	}
}

int main(int argc, char const *argv[])
{
	clock_t start, end;
	start = clock();
//--

	FILE *input = fopen("convertor.in", "rt");
	CHK(!input);

	FILE *output = fopen("convertor.out", "wt");
	CHK(!output);

	char *str = createString(input);

	removeGarbage(str, "{}[]:,");
	rmSpaceSel(str);

	int aux = 0;
	int nrEntries = 0;

	char **arr = malloc((strlen(str) + 1) * sizeof(char));
	CHK(!arr);
	int i = 0;

	char *p = strtok(str, "\"");
	char *firstField = (char*) strdup(p);

	while(p)
	{
		arr[i++] = p;
		//puts(p);

		if(strcmp(firstField, p))
			aux++;
		else
			nrEntries++;

		p = strtok(NULL, "\"");
	}

	int dist = 1 + aux / nrEntries; //distance between equal fields
	int nrFields = dist / 2;

	int j, k;

	//insert first line / fields names
	for(j = 0; j < nrFields; j++)
	{
		fprintf(output, "%s,", arr[2 * j]);
	}
	fprintf(output, "\n");

	//insert corresponding values
	for(j = 0; j < nrEntries; j++)
	{
		for(k = 0; k < nrFields; k++)
		{	
			fprintf(output, "%s,", arr[j * dist + 2 * k + 1]);
		}
		if(i != nrEntries - 1)
			fprintf(output, "\n");
	}
	
//--
	free(str);
	free(arr);
	free(firstField);
	fclose(input);
	fclose(output);

	end = clock();
	printf("%f\n", (double) (end - start) / CLOCKS_PER_SEC);
	return 0;
}