Binary File

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

/* Structure in C++ */
struct itemList {
	int item_no;
	string name;
	float price;
};

int main() {
	/* Opne binary file for write */
	ofstream wfile("info.dat", ios::out | ios::binary);

	/* Check error in file opening */
	if(!wfile) {
		cout << "Cannot open file!" << endl;
		return 1;
	}
	
	itemList wlists[3];

	wlists[0].item_no = 1;
	wlists[0].name = "Book";
	wlists[0].price = 150.50;
	
	wlists[1].item_no = 2;
	wlists[1].name = "Pen";
	wlists[1].price = 15.53;

	wlists[2].item_no = 3;
	wlists[2].name = "Pencil";
	wlists[2].price = 10.53;
	
	/* Write binary data using 'write()' */
	for(int i = 0; i < 3; i++)
	    wfile.write((char *) &wlists[i], sizeof(itemList));

	/* Close file for writing */
	wfile.close();

	/* Check file condition */
	if(!wfile.good()) {
		cout << "Error occurred at writing time!" << endl;
		return 1;
	}

	/* Open binary file for read */
	ifstream rfile("info.dat", ios::in | ios::binary);

	/* Check error in file opening */
	if(!rfile) {
		cout << "Cannot open file!" << endl;
		return 1;
	}
	
	itemList rlists[3];

	/* Read binary data using 'read()' */
	for(int i = 0; i < 3; i++)
	    rfile.read((char *) &rlists[i], sizeof(itemList));

	/* Close file for reading */
	rfile.close();

	/* Check file condition */
	if(!rfile.good()) {
		cout << "Error occurred at reading time!" << endl;
		return 1;
	}

	for(int i=0; i < 3; i++) {
		cout << "Item No: " << rlists[i].item_no << endl;
		cout << "Name: " << rlists[i].name << endl;
		cout << "Price: " << rlists[i].price << endl;
		cout << endl;
	}
	
	return 0;
}


/* Output */
Item No: 1
Name: Book
Price: 150.5


Item No: 2
Name: Pen
Price: 15.53


Item No: 3
Name: Pencil
Price: 10.53

Comments (0)

  • To add your comment please or

We use cookies to improve your experience on our site and to show you personalised advertising. Please read our cookie policy and privacy policy.

Got It!