-1

I need to save data the user input to a dat file, I got a description of an item, price, quantity my code is this, it doesn't save the data though

void saveInventory()
{
ofstream outfile;
outfile.open("inventory.dat", ios::binary);
if(!outfile.is_open()){
    cout<<"File openning error."<<endl;
    return;
}
outfile.write((char*)&items, sizeof(items));
outfile.close();
}
  • 3
    Please show a [mcve] – Jabberwocky Dec 02 '20 at 08:33
  • A pure function with arguments and types would make it so much easier to see what you actually try to save. – BitTickler Dec 02 '20 at 08:33
  • still waiting for experienced user – JohnJoryJr Dec 02 '20 at 08:49
  • @Scheff Sorry, I don't know what to tell you but I got to let you go – JohnJoryJr Dec 02 '20 at 08:54
  • 1
    About Serialization and Deserialization (the general cases of saving and loading): there is a whole side on the C++ FAQ: [**Serialization and Unserialization**](https://isocpp.org/wiki/faq/serialization) which I can warmly recommend as a start. – Scheff's Cat Dec 02 '20 at 08:56
  • 1
    Unfortunately, you didn't expose how `items` is defined. (Hence, the request for a [mcve].) Say, `items` is defined as `std::vector items;` then your write will not do what you expect. The `std::vector` is a wrapper where contents is stored on heap and managed/pointed to internally. Hence, your `write()` will write this pointer only without considering the actual contents you intend to write. (Better?) ;-) – Scheff's Cat Dec 02 '20 at 08:58
  • Btw. I just remembered that I already wrote an answer for a similar question. FYI: [SO: After writing a structure into a binary file, the file still has normal characters instead of unreadable ones](https://stackoverflow.com/a/58752800/7478597). – Scheff's Cat Dec 02 '20 at 09:07

1 Answers1

0

You may have to write something like:

    outfile.write((char*)&items[0], items.size() * sizeof(item));