binary input/output

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

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

#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;
	cin >> iname;
	ifstream ifs{ iname.c_str(), 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);

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

	if (!ofs) error("can't open output file", 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 << x << endl;
	}

	//...do something...

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

	//return 0;
	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_1.txt
Please enter output file name
ch10_9_output_1.txt
Please enter a character to exit
Input-File: ch10_9_input_1.txt
this is a test
Output-File: ch10_9_output_1.txt
this is a te

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.