I am trying to write a vector of class "Product" in to a file and read it back. However I get garbage loaded while reading. Can somebody review what could be possibly going wrong? Or suggest an alternate method.
#include <fstream>
#include <vector>
#include <iostream>
class Product
{
public:
std::string name;
int code;
double price;
};
int
main ()
{
const char *const file_name = "products.bin";
{
std::vector < Product > prod
{
Product {"Honey", 1, 12.34},
Product {"CoffeeBeans", 2, 56.78},
Product {"Cl", 3, 90.12}
};
for (const Product & p:prod)
std::cout << p.name << ' ' << p.code << ' ' << p.price << '\n';
std::ofstream file (file_name, std::ios::binary);
size_t sz = prod.size ();
file.write (reinterpret_cast < const char *>(&sz), sizeof (sz));
file.write (reinterpret_cast < const char *>(&prod[0]), sz * sizeof (prod[0]));
}
{
std::vector < Product > prod;
std::ifstream file (file_name, std::ios::binary);
size_t sz;
file.read (reinterpret_cast < char *>(&sz), sizeof (sz));
prod.resize (sz);
file.read (reinterpret_cast < char *>(&prod[0]), sz * sizeof (prod[0]));
for (const Product & p:prod)
std::cout << p.name << ' ' << p.code << ' ' << p.price << '\n';
}
}
> Blockquote