Segmentation fault function fgets

1

I'm having a segmentation fault problem opening txt files. I know for handling strings , higher level links, however I can not learn now, so I'm using C . My problem is to read a list with four thousand files name, whose format of each is as follows:

0.00053714,0.00053714,-0.00061595,0.30794,-0.00061595,0.30794,1.0001,1,0.0050735

My program takes the element that matches the position defined by the variable posição_elemento=6 , in this specific case equal to six. The problem that is occurring is that I can not perform this operation to get the sixth element in my four thousand files, with segmentation fault occurring. I think it's some wrong parameter I'm passing to while (fgets(line, sizeof(line), arquivo2)) . Here is my code below:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void subs(char* buffer){
   int i;
   for(i = 0; i < strlen(buffer); i++){
      if(buffer[i] == '\n')
         buffer[i] = 0; // Contrabarra zero: fim do buffer
   }
}
int main(){

   FILE *lista, *lista_nova;
   FILE *arquivo, *arquivo2;

   char buffer[50];
   char leia, line[256], *valor, *valor_escolhido;
   int cont_elemento = 1, posicao_elemento=6, i=0;
   float tempo;

   lista_nova = fopen ("lista_nova.txt", "r");

   arquivo = fopen("velocidades.txt", "wt");
   if (arquivo == NULL){
      printf ("Error opening velocidades\n");
      return 0;
      }

   while( !feof(lista_nova) ){
      fgets(buffer, 50, lista_nova);
      subs(buffer);
      arquivo2 = fopen(buffer, "r");

      if (arquivo2 == NULL){
         printf ("Error opening buffer.txt\n");
         return 0;
      }

      printf ("Arquivo = %s\n", buffer);

      while (fgets(line, sizeof(line), arquivo2))
    {
        //Pega o primeiro elemento separado por uma virgula.
        valor = strtok(line,",");

        //Obtem os outros elementos até o fim da linha.
        while (valor != NULL)
        {
            //printf("%s\n",valor);
            valor = strtok(NULL, ",");

            cont_elemento++;

            if (cont_elemento == posicao_elemento)
                valor_escolhido = valor;
        }
    }
    tempo=0.1*i;
    fprintf(arquivo,"%f\t%s\n",tempo,valor_escolhido);
    i++;
    cont_elemento=1;
   }

   fclose(arquivo);
   fclose(arquivo2);
   fclose (lista_nova);

return(0);
}
    
asked by anonymous 26.01.2016 / 18:16

1 answer

2

The "open" of arquivo2 and its "close" are not at the same level.

One runs in one cycle, another runs out of cycle.

while (/* ... */) {
    /* ... */
    arquivo2 = fopen(/* ... */);
    /* ... */
}
/* ... */
fclose(arquivo2);

Tip: Use a consistent indentation style.

    
28.01.2016 / 17:59