I'm writting a program for a car rental system. One of the functionalities should be updating car information in the binary file, but it isn't rewriting it at all. Here's what the struct looks like:
typedef struct {
int id;
char placa[8];
char modelo[10];
float motor;
int ar;
char cor[6];
int ano;
int kilo;
float diaria;
int dispo;
} Carros;
This is the function that is supposed to update the file, after searching for a specific car (I basically tried to use the same logic from the function that finds specific cars and prints them out.):
void updateCarro() {
FILE *fp = fopen("Carros.dat", "rb+");
Carros carro;
int id, size, cont, regs;
scanf("%d", &id); //variable to find a specific car's ID
//read new information that'll rewrite the old.
scanf(" %d", &carro.id);
scanf(" %s", carro.placa);
scanf(" %s", carro.modelo);
scanf(" %f", &carro.motor);
scanf(" %d", &carro.ar)
scanf(" %s", carro.cor);
scanf(" %d", &carro.ano);
scanf(" %d", &carro.kilo);
scanf(" %f", &carro.diaria);
scanf(" %d", &carro.dispo);
if(fseek(fp, 0, SEEK_END) == -1) {
printf("Erro ao localizar o registro\n");
return;
}
size = ftell(fp);
if(size == -1) {
printf("Não há registros\n");
return;
}
if(fseek(fp, 0, SEEK_SET) == -1) {
printf("Erro ao localizar o registro\n");
return;
}
records = size / sizeof(Carros);
for(cout = 0; cout < regs; count++) {
fread(&carro, sizeof(Carros), 1, fp);
if(carro.id == id) {
fwrite(&carro, sizeof(Carros), 1, fp);
break;
}
}
}
Here's the function that looks for a car's ID in the binary file and prints all the information. It seems to work, I tested multiple times, but maybe there's a flaw that's relevant. It's probably very easy to tell I'm not very experienced, so any help is welcome.
void mostraCarro() {
Carros carro;
FILE *fp = fopen("Carros.dat", "rb");
int id;
size_t count, records;
long size;
printf("entre com a indentificação do carro: \n");
scanf("%d", &id);
if(fseek(fp, 0, SEEK_END) == -1) {
printf("Erro ao localizar o registro\n");
return;
}
size = ftell(fp);
if(size == -1) {
printf("Não há registros\n");
return;
}
if(fseek(fp, 0, SEEK_SET) == -1) {
printf("Erro ao localizar o registro\n");
return;
}
records = size / sizeof(Carros);
for(count = 0; count < records; count++) {
fread(&carro, sizeof(Carros), 1, fp);
if(carro.id == id) {
printf("Identificação: %d\n", carro.id);
printf("Placa: %s\n", carro.placa);
printf("Modelo: %s\n", carro.modelo);
printf("Motor: %f\n", carro.motor);
printf("Ar condicionado: %d\n", carro.ar);
printf("Cor: %s\n", carro.cor);
printf("Ano: %d\n", carro.ano);
printf("Quilometragem: %d\n", carro.kilo);
printf("Valor da diária: %f\n", carro.diaria);
printf("Disponibilidade: %d\n", carro.dispo);
break;
}
}
fclose(fp);
}