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

Asked

Viewed 56 times

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, take the data that is saved in it, and save in an array of type INFO. My program compiles perfectly, but when I print the data of each vector position, all fields, less enrollment and salary, are empty.

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

So I kindly ask someone to show me how to permanently record the data in my vector.
Thank you =)

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 was defined as follows:

typedef struct informacoes{

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

}INFO;
  • In this case, if you read without this NULL will not work? try to pass to struct with the auxiliary variables. Try there to see if it works.

1 answer

1


You need to remember that the array line is local and the function Strtok returns a pointer to some position of that array, so you can’t just copy that address to your 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 released when the function ends.

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.