binary write

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

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

#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 iname = "output/";
	string in;
	cin >> in;
	iname += in;	
	ifstream ifs{ iname }; //note: stream mode
											 //binary tells the stream not to try anything clever with the bytes

	if (!ifs) error("can't open input file", iname);

	//open an ostream for binary output to a file:
	cout << "Please enter output file name\n";
	string oname = "output/";
	string on;
	cin >> on;
	oname += on;
	ofstream ofs{ oname }; //note: stream mode
											 //binary tells the stream not to try anything clever with the bytes

	vector<int> v;
	for (int x; ifs >> x;) { //note: reading bytes
		v.push_back(x);
	}

	for (int x : v) { //char x : v
		ofs.write(as_bytes(x), sizeof(int)); //note: writing bytes
	}

	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
p409_9_read_out.txt
Please enter output file name
p409_9_write_out.txt
Please enter a character to exit
Input-File: p409_9_read_out.txt
1684955424
544174880
1948283753
Output-File: p409_9_write_out.txt
 and so is t

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.