add to id +1 every time a new registration is made

Asked

Viewed 39 times

0

add "+1" every time I register

the program gives a constant id and does not change with a new registration

void cadastroCliente(){
    system("cls");
    FILE *arquivo_cliente;
    CLIENTE clt;
    arquivo_cliente = fopen("cliente.dat","ab");
    if(arquivo_cliente ==NULL){
        printf("Problemas na abertura do arquivo");
    }else{



        do{

            fflush(stdin);
            printf("Digite o nome: ");
            gets(clt.nome);
            fflush(stdin);
            printf("Digite o CPF: ");
            gets(clt.cpf);
            fflush(stdin);
            printf("Digite o email: ");
            gets(clt.email);
            fflush(stdin);
            printf("Digite o Telefone: ");
            gets(clt.telefone);

            fwrite(&clt,sizeof(CLIENTE),1,arquivo_cliente);
            printf("\nDeseja continuar(s/n)");

        }while(getch() =='s');
        fclose(arquivo_cliente);
    }
}

int acrescentarIdCliente(FILE *arquivo_cliente){
    unsigned long ultimID, id;
    CLIENTE clt;
    clt.id =0;
    ultimID=1;
    fseek(arquivo_cliente,0,SEEK_SET);
    while(fread(&clt,sizeof(CLIENTE),1,arquivo_cliente)==1){

          if(clt.id>=ultimID){
             id++;
             ultimID=id;
          }
          else
            return id;
       }
    return id;

}
´´´
  • To get generic you can first read the entire file and get the largest value ever registered, then just add 1. Depending on how you handle any changes and deletions in the file it is possible to optimize this process.

  • Your program is not good. Understand that id is local to the function and every call starts to exist again. Study variable scope. If you want to keep the value of id should state how static. Write around the data: it’s much simpler: create a Client structure. And a Register structure that groups.... customers, of course. Do not use fflush() for input. NEVER use gets(). Make it simple.

1 answer

0


I believe that only in order to read and increase the id, the problem lies in the fact that it is using the pointer to the file that was opened for bytes writing:

Function cadastroCliente:

FILE* arquivo_cliente = fopen("cliente.dat","ab");

As you opened the file for writing, you need to open a new read buffer within the function acrescentarIdCliente:

FILE* arquivo_cliente = fopen("cliente.dat","rb");

What can also be done is to open a buffer for reading and writing (append) and continue passing the pointer as argument to the function:

FILE* arquivo_cliente = fopen("cliente.dat","ab+");

I believe that this link with references in English can help.

Browser other questions tagged

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