#include <iostream>
#include <vector>
#include <string>
#include <fstream>
#include <sstream>
#include <iterator>
using std::ofstream;
using std::ifstream;
using std::string;
using std::cout;
using std::cin;



void alphabetizeSentences(string fname) {
	string outfile;
	std::ifstream read(fname);
	if (read) {
		/*
		* Get the size of the file
		*/
		read.seekg(0, std::ios::end);
		std::streampos length = read.tellg();
		read.seekg(0, std::ios::beg);

		/*
		* Use a vector as the buffer.
		* It is exception safe and will be tidied up correctly.
		* This constructor creates a buffer of the correct length.
		*
		istream& read (char* s, streamsize n)
		read block of data
		Extracts n characters from the stream and stores them in the array pointed to by s.

		This function simply copies a block of data, without checking its contents nor
		appending a null character at the end.  If the input sequence runs out of characters
		to extract (i.e., the end-of-file is reached) before n characters have been
		successfully read, the array pointed to by s contains all the characters read until
		that point, and both the eofbit and failbit flags are set for the stream.

		Internally, the function accesses the input sequence by first constructing a sentry object
		(with noskipws set to true). Then (if good), it extracts characters from its associated
		stream buffer object as if calling its member functions sbumpc or sgetc, and finally
		destroys the sentry object before returning.

		The number of characters successfully read and stored by this function can be accessed by
		calling member gcount.

		* Then read the whole file into the buffer.
		*/
		std::vector<char> buffer(length);
		read.read(&buffer[0], length);
		//cout << "buffer = ";
		//for(char& ch : buffer) cout << ch;
		/*
		* Create your string stream.
		* Get the stringbuffer from the stream and set the vector as it source.
		*/
		std::stringstream localStream;
		localStream.rdbuf()->pubsetbuf(&buffer[0], length);
		cout << "what file would you like to write to? ";
		cin >> outfile;
		ofstream write(outfile.c_str());
		localStream << outfile;
		std::copy(buffer.begin(), buffer.end(), std::ostream_iterator<char>(localStream));
		std::cout << localStream.str() << std::endl;
		//ofstream write(localStream);
		outfile << localStream.rdbuf();
		/*
		* Note the buffer is NOT copied, if it goes out of scope
		* the stream will be reading from released memory.
		*/
	}
}

int main() {
	string fname;
	cout << "\nWhat file would you like to read from?";
	cin >> fname;
	alphabetizeSentences(fname);
	cin.ignore();
	cin.get();
}