Cod sursa(job #1361189)

Utilizator SergiuVCioaca Valentin SergiuV Data 25 februarie 2015 20:04:06
Problema Convertor Scor 80
Compilator c Status done
Runda rosedu_cdl_2015 Marime 1.77 kb
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>

#define MAX 256

void write_in_file(char **words, int n, int seq, FILE *out) {
	int i;

	for (i = 0; i < seq; i = i+2) {
		fprintf(out, "%s", words[i]);
		fprintf(out, "%c", ',');
	}

	fprintf(out, "%c", '\n');
	int k = 0;
	for (i = 1; i < n; i = i + 2) {
		fprintf(out, "%s", words[i]);
		fprintf(out, "%c", ',');
		++k;
		if (k == seq / 2 ) {
			fprintf(out, "%c", '\n');
			k = 0;
		}
	}
}

int main() {
	FILE *in, *out;
	char buffer[MAX];
	if ((in = fopen("convertor.in", "rt")) == NULL) {
		fprintf(stderr, "Nu pot deschide fisierul\n");
		exit(-1);
	}

	if ((out = fopen("convertor.out", "wt")) == NULL) {
		fprintf(stderr, "Nu pot deschide fisierul\n");
		exit(-1);
	}

	int k = 0, i, count = 0, opened = 0, digit = 0;
	int start, seq = 0;
	char **words;

	words = (char**) malloc (200000 * sizeof(char*));

	while (fgets(buffer, MAX-1, in)) {
		for (i = 0; i < strlen(buffer); ++i) {
			if (buffer[i] == '{') seq = 0;
			if (buffer[i] == '"' && opened == 0) {
				opened = 1;
				start = i + 1;
				continue;
			}
			if (opened == 1) {
				++count;
			}
			if (buffer[i] == '"' && opened == 1) {
				words[k++] = (char *) malloc((count+1) * sizeof(char));
				strncpy(words[k-1], buffer+start, count-1);
				++seq;
				count = 0;
				opened = 0;
			}
			if (opened == 0 && (isdigit(buffer[i]) || buffer[i] == '.')) {
				++count;
				digit = 1;
				continue;
			} 
			if ((opened == 0) && (digit == 1) && (buffer[i] == ',')) {
				words[k++] = (char*) malloc((count+1) * sizeof(char));
				strncpy(words[k-1], buffer+(i-count), count);
				++seq;
				count = 0;
				digit = 0;
			}	

		}
	}

	write_in_file(words, k, seq, out);

	for (i = 0; i < k; ++i) 
		free(words[i]);
	free(words);

	fclose(in);
	fclose(out);

	return 0;
}