fread and structure memory allocation

0

I have the following structure:

typedef struct registro {//52 bytes
    char codigo[4];
    char descricao[31];
    char unidade[3];
    int quantidade;
    float valor;
    char status;
  }registro;

It should store the values of a dados.dat file, previously organized to be stored in this structure. To allocate space according to the groupings of items present in the memory aloco file dynamically through a record-type pointer. But at the time of pulling the data from the file and recording it in the structure the message "Writing error", present in the recording loop appears, and nothing is recorded in the structure. Here is the code:

void Ex10(){
    registro *lista;
    int i,cont=0;
    FILE *fp;
    char arquiv[100],caracter;

    puts("Digite o nome do arquivo(padrao:dados.dat):");
    scanf("%s",&arquiv);
    fp = fopen(arquiv,"r");

    while(!feof(fp)){
        caracter = getc(fp);
        cont++;
    }
    cont = cont - 1;
    cont = cont / 52;

    lista = malloc(cont * sizeof(registro));

    if(lista == NULL){
        printf("Erro de alocação de memória.\n");
        system("PAUSE");
    }else{
        puts("Alocado com sucesso!!");
    }

    for (i=0; i<cont; i++) {
        if (fread( &lista[cont], sizeof(struct registro), 1, fp) != 1) {//adiciona todos os dados.dat na estrutura
            puts("Erro na escrita.");
        }
    }

    for (i=0; i<cont; i++) {
        printf("Codigo = %s\n", lista[i].codigo);
        printf("Descricao  = %s\n\n", lista[i].descricao);
        printf("Unidade  = %s\n\n", lista[i].unidade);
        printf("Quantidade  = %d\n\n", lista[i].quantidade);
        printf("Valor  = %f\n\n", lista[i].valor);
        printf("Status  = %c\n\n", lista[i].status);
    }
}

If there is no dynamic allocation, the program normally writes the data in the structure, that is, when the declaration is done as follows: registro lista[6] , however this way it is necessary to know how much information exists inside the file, it will always be possible.

    
asked by anonymous 31.10.2016 / 01:37

1 answer

1

The problem is that you are reading the whole file to calculate the size. Before reading it back to the structure, you need to fseek() to go back to the beginning.

There are more efficient ways to calculate file size. See ftell() and fstat() . These functions give you the file size without having to read all the content.

    
31.10.2016 / 19:46