Cod sursa(job #1350994)

Utilizator info_maniacStefanescu Andrei info_maniac Data 21 februarie 2015 02:27:24
Problema Convertor Scor 70
Compilator c Status done
Runda rosedu_cdl_2015 Marime 2.64 kb
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<ctype.h>

#define OK 0
#define CCHAR -2 /* control char */

#define MAX_KEY 50

/* usual filesystem block size is 4 KB
 * so a read of 4 KB should minimize the time
 * spent on IO.
 * */
#define BLOCK_SIZE 4096 


int skip_to_char(char **str, char *orig, char c, char ctrl, FILE *fp) {
	while(**str != c) {
		if(**str == ctrl) {
			return CCHAR;
		}

		++ *str;
		if(**str == '\0') {
			*str = orig;
			fgets(*str, BLOCK_SIZE, fp);
			if(feof(fp)) {
				return EOF; 
			}
		}
	}

	return OK;
}


int main() {

	FILE *in, *out;

	in = fopen("convertor.in", "rt");
	out = fopen("convertor.out", "wt");

	char *string = malloc(BLOCK_SIZE * sizeof(char));
	short number_of_keys = 0;
	char *temp_string = string;

	fgets(temp_string, BLOCK_SIZE, in);

	/* read labels*/
	
	while(skip_to_char(&temp_string, string, '"', '}', in) == OK) {
		++ temp_string; /* skip " char */
		while(*temp_string !=  '"') {
			fprintf(out, "%c", *temp_string);
			++ temp_string;

			if(temp_string == '\0') {
				temp_string = string;
				fgets(temp_string, BLOCK_SIZE, in);
			}
		}

		fprintf(out, ",");
		++ number_of_keys;
		++ temp_string; /* skip the last " */
		if(skip_to_char(&temp_string, string, ',', '}', in) == CCHAR) {
			break;
		}
	}
		
	fprintf(out, "\n");
	fseek(in, 0, SEEK_SET);
	temp_string = string;
	fgets(temp_string, BLOCK_SIZE, in);
	
	/* read values */
	short k = 1;	
	while(!feof(in)) {
		skip_to_char(&temp_string, string, ':', 0, in);
		if(feof(in)) break;

		++ temp_string;
		if(*temp_string == '\0') {
			temp_string = string;
			fgets(temp_string, BLOCK_SIZE, in);
			if(feof(in)) break;
		}

		while(!isdigit(*temp_string) && !(*temp_string == '"')) {
			++ temp_string;
			if(temp_string == '\0') {
				temp_string = string;
				fgets(temp_string, BLOCK_SIZE, in);
				if(feof(in)) break;
			}
		}

		if(isdigit(*temp_string)) {
			while(isdigit(*temp_string)) {
				fprintf(out, "%c", *temp_string);
				++ temp_string;
				if(*temp_string == '\0') {
					temp_string = string;
					fgets(temp_string, BLOCK_SIZE, in);
					if(feof(in)) break;
				}
			}
		} else {
			++ temp_string;
			if(*temp_string == '\0') {
					temp_string = string;
					fgets(temp_string, BLOCK_SIZE, in);
					if(feof(in)) break;
			}
			
			while(*temp_string != '"') {
				fprintf(out, "%c", *temp_string);
				++ temp_string;
				if(*temp_string == '\0') {
					temp_string = string;
					fgets(temp_string, BLOCK_SIZE, in);
					if(feof(in)) break;
				}
			}

		}

		if(k == number_of_keys) {
			k = 1;
			fprintf(out, ",\n");
		} else {
			++ k;
			fprintf(out, ",");
		}
	}	

			
	free(string);
	fclose(in);
	fclose(out);
	

	return 0;
}