I want to save the following struct into a binary file:
struct Usuario{
char nombre[256];
char apellido[256];
char ingresos[256];
std::vector<Bill> manejador_facturas;
};
Bill is also a struct:
struct Bill{
float monto;
int dia;
int mes;
int anio;
char empresa[256];
};
What I tried to write the information into the binary file was:
void Perfil::GuardarEnBinario(std::ostream &archivo) {
Usuario reg;
Bill auxiliar;
strcpy(reg.nombre, nombre.c_str());
strcpy(reg.apellido, apellido.c_str());
strcpy(reg.ingresos, ingresos.c_str());
for(size_t i = 0; i < manejador_facturas.size(); i++){
strcpy(auxiliar.empresa, manejador_facturas[i].empresa);
auxiliar.monto = manejador_facturas[i].monto;
auxiliar.dia = manejador_facturas[i].dia;
auxiliar.mes = manejador_facturas[i].mes;
auxiliar.anio = manejador_facturas[i].anio;
reg.manejador_facturas.push_back(auxiliar);
}
archivo.write((char*)®, sizeof(reg));
}
At first I thought it worked because the .exe worked fine, but the problem is that the information that I saved, wasn't showing at all when I tried to see it (don't know if the .bin was corrupted or what). The code for reading the struct is:
void Perfil::LeerDesdeBinario(std::istream &archivo) {
Usuario reg;
Bill auxiliar;
archivo.read((char*)®, sizeof(reg));
nombre = reg.nombre;
apellido = reg.apellido;
ingresos = reg.ingresos;
for(size_t i = 0; i < reg.manejador_facturas.size(); i++){
strcpy(auxiliar.empresa, reg.manejador_facturas[i].empresa);
auxiliar.monto = reg.manejador_facturas[i].monto;
auxiliar.dia = reg.manejador_facturas[i].dia;
auxiliar.mes = reg.manejador_facturas[i].mes;
auxiliar.anio = reg.manejador_facturas[i].anio;
manejador_facturas.push_back(auxiliar);
}
}
archivo.read((char*)®, sizeof(reg));once you have the vector or any other non pod type in the structure this method of reading and writing the structure is no longer an option.