Cod sursa(job #1351854)

Utilizator info_maniacStefanescu Andrei info_maniac Data 21 februarie 2015 11:38:58
Problema Convertor Scor 90
Compilator c Status done
Runda rosedu_cdl_2015 Marime 2.61 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 * 2)
 
#define check(temp_string, orig, in)	if(*temp_string == '\0') {			   \
											temp_string = orig;				   \
											fgets(temp_string, BLOCK_SIZE, in);\
											if(feof(in)) break;				   \
										}											


#define skip_to_char(str, orig, c, ctrl, fp) do { 							\
												while(**str != c) {			\
													check(*str, orig, fp);	\
													if(**str == c) {		\
														break;				\
													}						\
													if(**str == ctrl) {		\
														break;				\
													}						\
													++ *str;				\
												}							\
												break;						\
											} while(0)


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(1) {
		skip_to_char(&temp_string, string, '"', '}', in);
		++ temp_string; /* skip " char */
		check(temp_string, string, in);

		while(*temp_string !=  '"') {
			fprintf(out, "%c", *temp_string);
			++ temp_string;

			check(temp_string, string, in);	
		}

		fprintf(out, ",");
		++ number_of_keys;
		++ temp_string; /* skip the last " */
		skip_to_char(&temp_string, string, ',', '}', in);

		if(*temp_string == '}') {
			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)) {
		check(temp_string, string, in);	

		skip_to_char(&temp_string, string, ':', 0, in);
		if(feof(in)) break;

		++ temp_string;
		check(temp_string, string, in);

		//skip_str(&temp_string, string, " \t\n", in);
		while(!isdigit(*temp_string) && !(*temp_string == '"')) {
			++ temp_string;
			check(temp_string, string, in);
			fflush(stdout);
		}

		if(isdigit(*temp_string)) {
			while(isdigit(*temp_string)) {
				fprintf(out, "%c", *temp_string);
				++ temp_string;
				check(temp_string, string, in);
			}
		} else {
			++ temp_string;
			check(temp_string, string, in);	
			
			while(*temp_string != '"') {
				fprintf(out, "%c", *temp_string);
				++ temp_string;
				check(temp_string, string, in);
			}

		}

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

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

	return 0;
}