Cod sursa(job #1361633)

Utilizator SergiuVCioaca Valentin SergiuV Data 25 februarie 2015 22:37:18
Problema Convertor Scor 100
Compilator c Status done
Runda rosedu_cdl_2015 Marime 2.01 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;
    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 i = 0, k = 0, count = 0, opened = 0, seq, digit = 0;
    char **words, buffer[MAX], c;

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

    while ((c = fgetc(in)) != EOF) {
        if ((char)c == '{') seq = 0;
        if (c == '"' && opened == 0) {
            opened = 1;
            continue;
        }
        if (opened == 1) {
            buffer[i++] = c;
            ++count;
        }
        if ((char)c == '"' && opened == 1) {
            opened = 0;
            words[k++] = (char *) malloc((count+1) * sizeof(char));
            strncpy(words[k-1], buffer, count-1);
            ++seq;
            count = 0; i = 0;
        }
        if (opened == 0 && isdigit(c)) {
            ++count;
            buffer[i++] = c;
            digit = 1;
        }
        if (opened == 0 && !isdigit(c) && digit == 1) {
            words[k++] = (char*) malloc((count+1) * sizeof(char));
            strncpy(words[k-1], buffer, count);
            ++seq;
            count = 0; i = 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;
}