Cod sursa(job #1354298)

Utilizator RaresvisRares Visalom Mihail Raresvis Data 21 februarie 2015 19:07:42
Problema Convertor Scor 100
Compilator c Status done
Runda rosedu_cdl_2015 Marime 2.32 kb
#include<stdio.h>
#include<stdlib.h>


void keys(FILE* f, FILE* g, int* keyLenght, int* keyIndex)
{
  int keyFlag = 1, stringFlag = 0, currentKeyLength = 0, strlen = 0;
  char x = 0, string[1000000];
  
  string[0] = '\0';

  while(x != '}'){
    x = getc(f);
    
    //if a string begins or ends
    if(x == '"'){
      stringFlag ^= 1;
    }
    //if x is a char
    else if(keyFlag && stringFlag){
      fprintf(g, "%c", x);
      currentKeyLength++;
    }
    //if the value of a key follows
    else if(x == ':'){
      keyFlag = 0;
      fprintf(g, ",");
      
      keyLenght[*keyIndex] = currentKeyLength;
      
      (*keyIndex)++;
    }
    //if a key follows
    else if(x == ','){
      keyFlag = 1;
      currentKeyLength = 0;
      
      string[strlen++] = ',';
    }
    else if(!keyFlag){
      if(stringFlag){
        string[strlen++] = x;
      }
      else if(x != '\n' && x != ' '){
	string[strlen++] = x;
      }
    }
  }
  
  string[strlen - 1] = ',';
  string[strlen] = '\0';
  
  fprintf(g, "\n");
  
  fprintf(g, "%s", string);
}


void CSV(FILE* f, FILE* g, int* keyLenght, int keyIndex)
{
  int valueFlag = 0, objectFlag = 0, stringFlag = 0, currentObjectKey = 0;
  char x = 0, buffer[1000];

  while(x != ']'){
    x = getc(f);
    
    if(x == '{'){
      objectFlag = 1;
      currentObjectKey = 0;
    }
    else if(x == '}'){
      objectFlag = 0;
      
      fprintf(g, ",");
    }
    else if(x == '"'){
      stringFlag ^= 1;
      
      if(stringFlag && !valueFlag){
	fread(buffer, sizeof(char), keyLenght[currentObjectKey], f);
      }
    }
    else if(x == ':'){
      valueFlag = 1;
    }
    else if(x == ','){
      valueFlag = 0;
      currentObjectKey++;
      
      if(objectFlag){
	fprintf(g, ",");
      }
      else{
	fprintf(g, "\n");
      }
    }
    else if (valueFlag && x != '\n' && x != ']'){
      if(stringFlag){
	fprintf(g, "%c", x);
      }
      else if(x != ' '){
	fprintf(g, "%c", x);
      }
    }
  }
}


int main()
{
  //open the files
  FILE* f = fopen("convertor.in", "r");
  FILE* g = fopen("convertor.out", "w");
  
  //get the keys
  int keyLenght[10100], keyIndex = 0;
  //keyLenght = (int*)malloc(200 * sizeof(int));
  keys(f, g, keyLenght, &keyIndex);

  //start getting the objects and teir values
  CSV(f, g, keyLenght, keyIndex);

  //close the files
  fclose(f);
  fclose(g);

  return 0;
}