Cod sursa(job #1360065)

Utilizator SergiuVCioaca Valentin SergiuV Data 25 februarie 2015 11:18:30
Problema Convertor Scor 70
Compilator c Status done
Runda rosedu_cdl_2015 Marime 1.82 kb
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>

#define MAX 256

void write_in_file(char **words, int n, FILE *out) {
	int i, count = 0;
	for (i = 1; i < n; ++i) {
		++count;
		if (strcmp(words[i], words[0]) == 0) break;
	}

	for (i = 0; i < count; 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 == count / 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, var = 0;
	int start;
	char **words;

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

	while (fgets(buffer, MAX-1, in)) {
		for (i = 0; i < strlen(buffer); ++i) {
			if (buffer[i] == '"' && opened == 0) {
				opened = 1;
				start = i + 1;
				continue;
			}

			if (buffer[i] == '"' && opened == 1) {
				opened = 0;
				words[k++] = (char *) malloc((count+1) * sizeof(char));
				strncpy(words[k-1], buffer+start, count);
				count = 0;
			}

			if (opened == 1) {
				++count;
			}

			if ((opened == 0) && (isdigit(buffer[i]) || isalpha(buffer[i]))) {
				++count;
				var = 1;
				continue;
			} 

			if ((opened == 0) && (var == 1) && (!isdigit(buffer[i]) || !isalpha(buffer[i]))) {
				words[k++] = (char*) malloc((count+1) * sizeof(char));
				strncpy(words[k-1], buffer+(i-count), count);
				count = 0;
				var = 0;
			}
		}
	}

	write_in_file(words, k, out);

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

	fclose(in);
	fclose(out);
	return 0;
}