I need to save a vector of structs on a binary file, and get this data back when the program starts again.
struct produc{
string nanme;
float price;
int id;
int idp;
};
vector <produc> products;
scanf("%s",des.c_str());
scanf("%d",&cod);
scanf("%d",&prov);
scanf("%f",&price);
produc pr;
pr.name = des.c_str();
pr.price=precio;
pr.id=cod;
pr.idp=prov;
products.push_back(pr);
This is how I ask for new data and put on a vector, then I just use a for to show the info.
int l = products.size();
produc pr;
for(int i=0;i<l;i++)
{
pr = productos[i];
cout << "\t Code : " << pr.id << endl;
cout << "\t Product : " << pr.nombre << endl;
cout << "\t Prov Code. : " << pr.idp << endl;
cout << "\t Priceo : " << pr.precio << endl << endl;
}
I would like to save this vector on a binary file, if i close the program recover it and put it on a vector. I was following the answer on this post but I struggling and not sure how implement it How to read / write a struct in Binary Files?
Edited.
I actually try to write/read individually my struct, but I was wondering if was an option to save the whole vector. Either way how I do it doest work cuz when I try to read back I got an Error: Segmentation fault (core dumped) This is how I write:
ofstream fichero("produts.data", ios::app | ios::binary);
if(!fichero) {
cout << "Can't open";
}
fichero.write((char *) &pr, sizeof(produc));
fichero.close();
read:
ifstream fichero("produts.data", ios::in | ios::binary);
if(!fichero){
cout << "Can't open";
exit(0);
}
fichero.read((char *)&pr,sizeof(produc));
fichero.close();