Pagini recente » Cod sursa (job #129667) | Cod sursa (job #2458459) | Cod sursa (job #1331133) | Cod sursa (job #2439) | Cod sursa (job #1350385)
#include<stdio.h>
#include<stdlib.h>
void keys(FILE* f, FILE* g, int* keyLenght, int* keyIndex)
{
int keyFlag = 1, stringFlag = 0, currentKeyLength = 0;
char x = 0;
while(x != '}'){
x = getc(f);
while(x == ' ' && !stringFlag){
x = getc(f);
}
//if a key follows
if(x == ','){
keyFlag = 1;
currentKeyLength = 0;
}
//if the value of a key follows
else if(x == ':'){
keyFlag = 0;
fprintf(g, ",");
keyLenght[*keyIndex] = currentKeyLength;
(*keyIndex)++;
}
//if a string begins or ends
else if(x == '"'){
stringFlag ^= 1;
}
//if x is a char
else{
if(keyFlag && stringFlag){
fprintf(g, "%c", x);
currentKeyLength++;
}
}
}
fprintf(g, "\n");
}
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);
while(x == ' ' && !stringFlag){
x = getc(f);
}
if(x == '{'){
objectFlag = 1;
currentObjectKey = 0;
}
else if(x == '}'){
objectFlag = 0;
fprintf(g, ",");
}
else if(x == '"'){
if(stringFlag){
stringFlag = 0;
}
else{
stringFlag = 1;
if(!valueFlag){
/*int i;
for(i = 0; i < keyLenght[currentObjectKey]; i++){
x = getc(f);
}*/
fgets(buffer, keyLenght[currentObjectKey], f);
//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(x == ']'){
objectFlag = 0;
valueFlag = 0;
}
else{
if(valueFlag && stringFlag /*&& x > 0*/ && x != '\n'){
fprintf(g, "%c", x);
}
else if(valueFlag && x != ' ' /*&& x > 0*/ && x != '\n'){
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);
//restart the position of the pointer in the file
fclose(f);
FILE* h = fopen("convertor.in", "r");
//start getting the objects and teir values
CSV(h, g, keyLenght, keyIndex);
//close the files
fclose(g);
fclose(h);
//free the memory
//free(keyLenght);
return 0;
}