I need to read each line of an input file, break it into tokens and save each token in a position of a struct. I'm able to do this partially, but at a certain point in the file, segmentation fault occurs and the program does not read the file completely. I've already visited other site posts, but I was unable to resolve my issue.
The input file and in the template:
RESULTADO,SWIMMING MEN'S 400 M FREESTYLE,OURO,CHINA,PRATA,SOUTH KOREA,BRONZE,UNITED STATES
RESULTADO,SWIMMING WOMEN'S 400 M INDIVIDUAL MEDLEY,OURO,CHINA,PRATA,UNITED STATES,BRONZE,CHINA
RESULTADO,WEIGHTLIFTING WOMEN'S 48 KG,OURO,CHINA,PRATA,JAPAN,BRONZE,NORTH KOREA
CONSULTA,BRAZIL
And the output file (as test), should be of type:
RESULTADO SWIMMING MEN'S 400 M FREESTYLE OURO CHINA PRATA SOUTH KOREA BRONZE UNITED STATES
RESULTADO SWIMMING WOMEN'S 400 M INDIVIDUAL MEDLEY OURO CHINA PRATA UNITED STATES BRONZE CHINA
RESULTADO WEIGHTLIFTING WOMEN'S 48 KG OURO CHINA PRATA JAPAN BRONZE NORTH KOREA
CONSULTA BRAZIL
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Frase{ //struct para guardar os tokens(em pos[40])
struct Linha{
char pos[40];
};
struct Linha teste[10];
};
struct Copia{//struct auxiliar para copia, le as linhas do arquivo de entrada
char frase[200];
};
struct Frase TOTAL[1000];
void LeArquivo(){
char * valor = (char *) malloc(40);
FILE *arq,*arq1;
int i;
struct Copia vetor[1000];//vetor auxiliar para copia
arq=fopen("teste.txt","r");//arquivo de entrada
arq1=fopen("saida.txt","w");//arquivo usado apenas pra testar se esta lendo corretamente
for(i=0;i<1000;i++){//percorre todos os espaços do vetor, parapoderimprimir no arquivo de saida de teste
while((fgets(vetor[i].frase,sizeof(vetor[i].frase),arq))!=NULL ){
valor = strtok(vetor[i].frase,",");
strcpy(TOTAL[i].teste[0].pos,valor);
fprintf(arq1,"%s ",TOTAL[i].teste[0].pos);
valor = strtok(NULL,",");
strcpy(TOTAL[i].teste[1].pos,valor);
fprintf(arq1,"%s ",TOTAL[i].teste[1].pos);
valor = strtok(NULL,",");
if(valor!=NULL){
strcpy(TOTAL[i].teste[2].pos,valor);
fprintf(arq1,"%s ",TOTAL[i].teste[2].pos);
valor = strtok(NULL,",");
strcpy(TOTAL[i].teste[3].pos,valor);
fprintf(arq1,"%s ",TOTAL[i].teste[3].pos);
valor = strtok(NULL,",");
strcpy(TOTAL[i].teste[4].pos,valor);
fprintf(arq1,"%s ",TOTAL[i].teste[4].pos);
valor = strtok(NULL,",");
strcpy(TOTAL[i].teste[5].pos,valor);
fprintf(arq1,"%s ",TOTAL[i].teste[5].pos);
valor = strtok(NULL,",");
strcpy(TOTAL[i].teste[6].pos,valor);
fprintf(arq1,"%s ",TOTAL[i].teste[6].pos);
valor = strtok(NULL,"\n");
strcpy(TOTAL[i].teste[7].pos,valor);
fprintf(arq1,"%s\n",TOTAL[i].teste[7].pos);
}
if(strcmp(TOTAL[i].teste[0].pos,"RESULTADO")==0)
{
printf("%s %s %s\n",TOTAL[i].teste[3].pos,TOTAL[i].teste[5].pos,TOTAL[i].teste[7].pos);
}
else printf("%s \n",TOTAL[i].teste[1].pos);
}}
free(valor);
fclose(arq1);
fclose(arq);
}
int main(){
LeArquivo();
return 0;
}