fread and structure memory allocation

Asked

Viewed 232 times

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 must store the values of a file dados.dat, previously organized to be stored in this structure. To allocate space according to the groupings of items present in the file allocates memory dynamically through a record type pointer. However, when pulling the data from the file and writing it in the structure the message "Error in writing", present in the recording loop appears, and nothing is written in the structure. Here’s 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 saves the data into the structure, i.e., when the declaration is made as follows: registro lista[6], but in this way it is necessary to know how much information there is inside the file, something that will not always be possible.

1 answer

1


The problem is that you are reading the entire file to calculate the size. Before reading it again to the structure, you need to make a fseek() to get back to the beginning.

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

Browser other questions tagged

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