Binary save

Asked

Viewed 62 times

0

People, I have a structure of 10 fixed positions. Each of them has a vector whose size has been dynamically allocated. I am trying to save in binary file the information and then perform the reading of it but when I print the reading the data appear in disorder. Can someone help me ?

void terminar (principal *inicio){
    principal *temporario=inicio;
    principal *auxiliar=NULL;

    salvar_arquivo (inicio);

    for (temporario=inicio; temporario!=NULL; temporario=temporario->proximo){
        free (temporario->vetor);

        if (auxiliar!=NULL){
            free (temporario);
        }
        auxiliar=temporario;
    }

    if (auxiliar!=NULL){
        free (temporario);
    }

    exit (1);   
}

void salvar_arquivo (principal *inicio){
    FILE *arq;
    char tipo;

    do {
        printf ("Escolha um formato valido para salvar os dados (T/texto - B/binario):  ");
        scanf ("%s",&tipo);

        if (tipo == 'T'){
            arq = fopen ("trab2.txt","w");

                if (arq == NULL){
                    printf ("Erro ao tentar abrir o arquivo\n");
                    exit (1);
                } else              

            salvar_texto (inicio,arq);          
            fclose (arq);
        } 
        else {
                if (tipo == 'B'){
                    arq = fopen ("trab2.dat","wb");

                    if (arq == NULL){
                        printf ("Erro ao tentar abrir o arquivo\n");
                        exit (1);
                    } else 

                salvar_binario (inicio,arq);            
                fclose (arq);

                }
        }
    } while ((tipo!='T') && (tipo!='B'));

}

void salvar_texto (principal *inicio, FILE *arq){
    principal *aux_principal;

    for (aux_principal=inicio->proximo; aux_principal!=NULL; aux_principal=aux_principal->proximo){

        fprintf (arq, "\n%d,", aux_principal->tamanho);
        fprintf (arq, "%d,", aux_principal->numero);
        fprintf (arq, "%d,", aux_principal->fim);
        fprintf (arq, "%d;", aux_principal->posicao);

        for (int i=0; i<aux_principal->fim; i++){
            fprintf (arq, "%d;", aux_principal->vetor[i]);
        }

    }

}

void salvar_binario (principal *inicio, FILE *arq){
    principal *temp;

    for (temp=inicio->proximo; temp!=NULL; temp=temp->proximo){ 
        fwrite(&temp->tamanho, sizeof(principal), 1, arq);
        fwrite(&temp->numero, sizeof(principal), 1, arq);
        fwrite(&temp->fim, sizeof(principal), 1, arq);
        fwrite(&temp->posicao, sizeof(principal), 1, arq);

    //  fwrite(&temp->vetor, sizeof(int), temp->tamanho , arq);

        printf("SASASAS\n");
    } 

    printf ("\nArquivo salvo com sucesso !!");
}

void leitura_binario (principal *inicio,FILE *arq){
    principal *temp;

     while (!feof(arq)){
        temp = (principal*)malloc (sizeof( principal ));

        fread(temp, sizeof(principal), 1, arq);
        printf ("Tamanho: %d\n", temp->tamanho);
        printf ("numero: %d\n", temp->numero);
        printf ("posicao: %d\n", temp->posicao);

    }


    fclose (arq);
}

void leitura (principal *inicio){
    FILE *arq;
    char tipo;

    printf ("O arquivo gravado foi salvo em Binario ou Texto ? (B/Binario - T/Texto): ");
    scanf ("%c",&tipo);

    if (tipo == 'T'){
        arq = fopen ("trab2.txt","r");
        if (!arq){
            printf ("erro\n");
        }else leitura_texto (inicio,arq);
    } 
    else {
         if (tipo == 'B'){
            arq = fopen ("trab2.dat","rb");
        }
        if (!arq){
            printf ("erro\n");
        }else  leitura_binario (inicio,arq);
    }

}

void leitura_texto (principal *inicio,FILE *arq){
    principal *temp = inicio->proximo;

    if (arq == NULL){
            return;
    }

    for (temp=inicio->proximo; temp!=NULL; temp=temp->proximo){

        fscanf (arq, "\n%d,", &temp->tamanho);
        fscanf (arq, "%d,", &temp->numero);
        fscanf (arq, "%d,", &temp->fim);
        fscanf (arq, "%d;", &temp->posicao);

        if (temp->tamanho > 0){
             temp->vetor= (int *)malloc((temp->tamanho)*sizeof(int));  
             if (temp->vetor == NULL){
                    printf ("Memoria insuficiente\n");
             } else
                for (int i=0; i<temp->fim; i++){
                    fscanf (arq, "%d;", &temp->vetor[i]);
                }               
            }
    }

    fclose (arq);

}
  • It seems to me that in binary writing you save field by field but each one of them in space equivalent to a main structure when it should record a single time but the whole structure, which incidentally you did not show which is.

  • typedef struct structure { int size; int number; int *vector; int end; int position; struct structure *next; } main;

  • I even managed to save but at the time of reading it is as if he found the first position, did the reading correctly and then took some 6 garbage; finds the second, reads correctly and more garbage ... until the tenth

  • Note that if you record the main structure you will be recording a pointer to the vector and not the vector elements. Rethink what data you want to save to the file.

  • I followed your recording tip and now only reads the 10 positions (which is the size of my main structure). But in the print appears known numbers and the information is not found.

  • Data print: Position: 32764 Size: -1766804848 Number: 21947 End: -1676022528 Position: 32764 Size: -1766804800 Number: 21947 End: -1676022528 Position: 32764 Size: -1766804752 Number: 21947 End: -1676022528

  • But is the int * vector pointer still valid when you read this address from your file? I believe you have to write in your file all the elements of your vector and not only the main structure.

  • Yes, you’re correct. I left the vector last because I can’t do the basics yet

  • As I put in the first comment, here: fwrite(&temp->size, sizeof(main), 1, Arq); you are saving an int but in the space of the size of your main structure, but in the reading expect to read in this space the whole structure.

Show 4 more comments
No answers

Browser other questions tagged

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