Copy one binary file to another in C

Asked

Viewed 106 times

0

Good! I am creating a car management program, and I need to first insert my cars (structs) in a binary file (draft), and then use another function to update, and pass the structs of that binary to another (definitive binary).

In this case the structs have a variable "eliminate", and the only structs that pass to my definitive binary are the ones that (delete == 1). And the definitive file always has to do a reset and stick to the structs that the draft file passes to it, deleting any previously present content.

I can’t find the error, but the definitive file is not receiving anything.

These are my structs:

    struct Carro
{
char Marca[30];
char Modelo[30];
char Cor[30];
int Numero;
int eliminar;
} ficha[200];

This is my update function:

    FILE *fp, *fpdef;
    int retorno, i = 1;
    fpdef = fopen("Dados.bin","a");
    fp = fopen("Rascunho.bin", "rb");


    printf("\n =========================================");
    printf("\n =              Atualizar                =");
    printf("\n =========================================");


    retorno = fread(&ficha[i], sizeof(struct Carro), 1, fp);
    while ( retorno == 1) 
    {
        if(ficha[i].eliminar == 1)
        {
            fwrite(&ficha[i], sizeof(struct Carro), 1, fpdef);
        }
        i++;
    retorno = fread(&ficha[i], sizeof(struct Carro), 1, fp);
    }


    printf("\n\n\n Ficheiro Atualizado com sucesso!\n\n");
    system("pause");
    system("CLS");
    main();     
}

Thanks for the Help! :)

1 answer

0

int i starts at 0 at 1, you are not using the first vector position.

This is on the fread manpage: On Success, fread() and fwrite() Return the number of items read or Written. This number equals the number of bytes transferred only when size is 1.

It may be that your while condition is wrong, try putting the while >= 1, may solve.

I hope it helped you.

Browser other questions tagged

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