How to pass information from a file to a dynamic vector of C structures?

Asked

Viewed 629 times

0

Good afternoon! (EDITED) I’m doing a language work C, where I have to show on the console the information stored in a text file, but it is mandatory to pass all information to vetores structural dynamics. I think I’ve already done something, but when I try to keep the specialty in variável, the file ends up saving the following words.

Ex: O v->nome is guarding "Joao Silva" and the v->especialidade is saving "Neurology 9.30 - 17.00" and I intend to keep only "Neurology". Someone can help me?

struct hora_entrada { int horas, minutos; };

struct hora_saida {int horas, minutos; };

typedef struct medico med, *p_med;
struct medico {
  char nome[ST_TAM];
  char especialidade[ST_TAM];
  struct hora_entrada h_e;
  struct hora_saida h_s;
};

int le_dados () {

  FILE *f, *g;
  med *v;

  f = fopen("medico.txt", "rt");
  g = fopen("paciente.txt", "rt");
  if (f == NULL || g == NULL) {
    printf("Erro no acesso ao ficheiro.\n");
    return 0;
  }

v = malloc(sizeof(med));
if (v == NULL) {
  printf("Erro na alocaçao de memoria.\n");
  return 0;
}

while ((fscanf(f,"%49[^\n] %49[^\n]",v->nome, v->especialidade)) == 2)
  printf("%s\n%s",v->nome, v->especialidade);

fclose(f);

}

inserir a descrição da imagem aqui

  • But the fscanf was to read the first and last name only ? And in case it has more than 2 names as in Ana Maria Santos ? To read only the first name a %s is enough.

  • I want to read the whole file and save each word in a structure variable. In this case I want to keep "Joao" in one variable, "Silva" in another, "Neurology" in another and so on...

  • But the structure has nome_p and nome_s and the file has doctors with 3 names, how will that work?

  • You’re right, I hadn’t figured that out yet... so I have to keep the whole name on a variable and the rest on individual variables. You know how it’s done?

  • Yes, you are saving not only the specialty because your reading command (scanf) is setting to read to the end of the line (or by completing 49 characters). Rethink the format specification of your scanf. If the specialty name is always a single word then use only one %s, if the specialty name can contain spaces then specify the maximum size which, it seems to me, is 15 and not 49.

1 answer

0

Browser other questions tagged

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