Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Prodentim Probiotics Specially Designed For The Health Of Your Teeth And Gums

Instant Grammar Checker - Correct all grammar errors and enhance your writing

Teach Your Child To Read

Powerful WordPress hosting for WordPress professionals

Disclosure: My content contains affiliate links.

31,166 questions

40,722 answers

573 users

How to write and read class objects to binary file in C++

1 Answer

0 votes
#include <iostream>
#include <fstream>
 
using namespace std;

typedef struct product {
    long pcode;
    string pname;
    double price;
} product;

#define SIZE 3
 
int main ()
{
    product obj[] = {
            {.pcode = 98742,
             .pname = "Dell XPS 15 laptop 15.6 inch",
             .price = 1964.43
            },
            {.pcode = 67398,
             .pname = "Dell XPS 13 7390 Laptop 13.3 inch",
             .price = 1499.99
            },
            {.pcode = 79913,
             .pname = "Apple MacBook Pro 16-Inch 16GB RAM 1TB Storage",
             .price = 2562.41
            }};

    const char *FILENAME = "data.bin";
    
    ofstream o(FILENAME, ios::binary);
    for (int i = 0; i < SIZE; i++)
        o.write((char *) &obj[i], sizeof(product));
    o.close();


    ifstream is(FILENAME, ios::binary);
    product tmp;
    
    while(is.read((char *) &tmp, sizeof(product))) {
          cout << "pcode: " << tmp.pcode << endl;
          cout << "pname: " << tmp.pname << endl;      
          cout << "price: " << tmp.price << endl << endl;
    }
 
    is.close();
    
   return 0;
}
 
 
 
/*
run:
 
pcode: 98742
pname: Dell XPS 15 laptop 15.6 inch
price: 1964.43

pcode: 67398
pname: Dell XPS 13 7390 Laptop 13.3 inch
price: 1499.99

pcode: 79913
pname: Apple MacBook Pro 16-Inch 16GB RAM 1TB Storage
price: 2562.41
 
*/

 





answered Feb 14, 2020 by avibootz
edited Feb 14, 2020 by avibootz

Related questions

2 answers 101 views
1 answer 83 views
1 answer 39 views
1 answer 33 views
...