binary read

Bjarne Stroustrup “Programming Principles and Practice Using C++”
Chapter 11 Exercise 9 Read
Using std_lib_facilities.h by Bjarne Stroustrup.

//	Philipp Siedler
//	Bjarne Stroustrup's PPP
//	Chapter 11 Exercise 9 Read

#include "std_lib_facilities.h"

int main()
try
{
	//open an istream for binary input from a file:
	cout << "Please enter input file name\n";

	string in;
	string iname = "input/";
	cin >> in;
	iname += in;
	
	ifstream ifs{ iname, ios_base::binary }; //note: stream mode
	//binary tells the stream not to try anything clever with the bytes
	
	if (!ifs) error("can't open input file", iname);
	else {
		cout << "file opened" << endl;
	}

	//open an ostream for binary input from a file:
	cout << "Please enter output file name\n";

	string out;
	string oname = "output/";
	cin >> out;
	oname += out;

	ofstream ofs{ oname };
	
	vector<int> v;

	//read from binary file:
	for (int x; ifs.read(as_bytes(x), sizeof(int));) { //note: reading bytes
		v.push_back(x);
	}
		
	//cout binary file:
	for (int x : v) {
		cout << x << endl;
		ofs << x << endl;
	}	

	keep_window_open();
}
catch (runtime_error e) {
	cout << e.what() << endl;
	keep_window_open();
}
catch (...) {
	cout << "Exiting" << endl;
	keep_window_open();
}
Output:
Please enter input file name
ch10_9_input_2.txt
file opened
Please enter output file name
p409_9_read_out.txt
1684955424
544174880
1948283753
Please enter a character to exit
Input-File: ch10_9_input_2.txt
 and so is this
Output-File: p409_9_read_out.txt
1684955424
544174880
1948283753

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.