Create dynamic structures from a text file?

Asked

Viewed 65 times

0

I have data stored in a text file. I want to read the text file and store the data in my variables, then insert them in my function inserir_medico that will use the data to create a concatenated List. The problem is, 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), because I only have 3 doctors in my file (with their 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 are working with a text and non-binary file?

The contents of the text file are:

Joao Silva

Neurology 9.30 - 17.00

Ana Maria Santos

Pediatrics 10.00 - 19.00

Sandra Almeida

Dermatology 14.00 - 17.45

Function that fetches the file data to place in the list widgets:

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")
    }
}

1 answer

0

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

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

One more thing: don’t mix readings with fgets() and fscanf(). It is preferable to read always with fgets() and interpret the line with sscanf() next.

The correct way (with some added validations) 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++;
    }

Browser other questions tagged

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