Create dynamic structures starting from a text file?

0

I have data saved in a text file. I want to read the text file and store the data in my variables, and then insert them into my inserir_medico function that will use the data to create a concatenated List. The problem is that, I have a variable that counts the number of "doctors", this variable at the end of the program should be equal to 3 ( conta_med = 3 ), since I only have 3 doctors in my file (with their respective specialties and hours of entry and exit).

I wonder why in the end I get conta_med = 5 and not conta_med = 3 ? Is it because you're working with a text file and not binary?

The content of the text file is:

  

Joao Silva

     

Neurology 9.30 - 17.00

     

Ana Maria Santos

     

Pediatrics 10.00 - 19.00

     

Sandra Almeida

     

Dermatology 14.00 - 17.45

Function that will fetch the data from the file to put in the list elements:

int med_ficheiro(){

    FILE *fm;  char mnome[50], esp[50]; int h_entrada, h_saida;
    int conta_med=0;
    int linhas[100], z=0, x=0;
    char ch;
    inic_med();

        fm= fopen("medicos.txt","r");
        if(fm==NULL){
            printf("Impossivel abrir o ficheiro.\n");
            exit(1);
        }


         else{
        printf("\n\n\n");
        while(!feof(fm)){

           fgets(mnome,50,fm);

           fscanf(fm,"%s %f - %f", esp, &h_entrada, &h_saida);

           inserir_medico(mnome, esp, h_entrada, h_saida);
           conta_med++;



        } 
         printf("%d", conta_med); //AQUI DÁ ERRADO!!! PORQUE??? (MOSTRA "5")
    }
}
    
asked by anonymous 22.08.2016 / 02:41

1 answer

0

while(!feof(fm)) is wrong (see this question in the English OS ).

What happens is that the feof() function does not indicate if the next read will give error, it indicates if the last error was due to the file being at the end.

One more thing: Do not mix readings with fgets() and fscanf() . It is preferable to always read with fgets() and interpret the line with sscanf() .

The correct way (with some validations added) is

    while (fgets(mnome, sizeof mnome, fm)) {    // primeira linha
        // remover ENTER de mnome
        size_t mnomelen = strlen(mnome);
        if (mnome[mnonelen - 1] == '\n') {
            mnome[--mnomelen] = 0;
        }
        char temp[100];
        // segunda linha
        if (fgets(temp, sizeof temp, fm) == NULL) {
            fprintf(stderr, "Erro na leitura da segunda linha\n");
            exit(EXIT_FAILURE);
        }
        if (sscanf(temp, "%49s%f -%f", esp, &h_entrada, &h_saida) != 3) {
            fprintf(stderr, "Erro na interpretação da 2a linha\n");
            exit(EXIT_FAILURE);
        }
        inserir_medico(mnome, esp, h_entrada, h_saida);
        conta_med++;
    }
    
22.08.2016 / 11:20