Passing by reference, and saving data from a file to a vector

1

I'm having trouble saving the read data from a text file and a vector from a structure I created.

My goal is to open a text file, grab the data that is saved in it, and save it to a vector of type INFO. My program compiles perfectly, but when I put to print the data of each vector position, all fields, minus registration and salary, are empty.

I tried to send the address of the salvaDados(&pessoa) vector but that also went wrong.

So, kindly ask someone to show me how to permanently record the data in my vector. Thanks =)

void salvaDados(INFO pessoa[]) {

   FILE* f;
   char linha[200];


  f = fopen("teste.txt", "r");

   if(f == NULL){
      printf("Desculpa, banco de dados indisponível\n");
      exit(0);
  }


    // O fseek faz com que a barra se seleção pule para local indicado;
   //Nesses caso, a barra irá pular 49 bytes a partir da linha inicial(SEEK_SET);    

   fseek(f, 49, SEEK_SET);

   int i = 0;
   while((fscanf(f,"%s", linha)) != EOF) {

      char* tok;
      tok = strtok(linha, ",");

      while(tok != NULL) {

         sscanf(tok, "%d", &(pessoa[i].matricula));
         tok = strtok(NULL, ",");

        pessoa[i].nome = tok;
         tok = strtok(NULL, ",");
         pessoa[i].sobrenome = tok;
         tok = strtok(NULL, ",");
         pessoa[i].email = tok;
         tok = strtok(NULL, ",");
         pessoa[i].telefone = tok;
         tok = strtok(NULL, ",");

         sscanf(tok, "%f", &(pessoa[i].salario));
         tok = strtok(NULL, ",");

      }

    i++;

  }


}

My struct has been defined as follows:

typedef struct informacoes{

  int matricula;
  char* nome;
  char* sobrenome;
  char* email;
  char* telefone;
  float salario;

}INFO;
    
asked by anonymous 20.08.2017 / 06:13

1 answer

1

You need to remember that the array array is local and that the strtok function returns a pointer to some position in that array, so you can not simply copy that address for its structure because the data in that array will be overwritten in the next iteration (invalidating the previous data) and the memory space where line is allocated will be freed when the function is finished.

The solution would be to allocate a space for each field (name, surname, email and phone) and use the strcpy function to pass values to those fields.     

21.08.2017 / 16:15