// PersistStream.cpp #include #include #include #include ///////////////////////////////////////////////////////////// // Required solution starts here // class PersistStream { public: PersistStream(); PersistStream(const std::string& filename, const std::string& msg); ~PersistStream(); template PersistStream& operator<<(const T& t); std::string say(); private: static std::ofstream out; }; std::ofstream PersistStream::out; PersistStream::PersistStream() { if(!out.good()) throw exception("\n stream not attached to file\n\n"); } PersistStream::PersistStream( const std::string& filename, const std::string &msg) { out.open(filename.c_str()); if(!out.good()) throw exception("\n can't open file"); out << msg; } PersistStream::~PersistStream() { // don't close stream out, since it is static; } template PersistStream& PersistStream::operator<<(const T& t) { out << t; return *this; } // Required solution ends here ///////////////////////////////////////////////////////////// std::string PersistStream::say() { out.close(); std::ostringstream temp; std::ifstream in("temp.tmp"); temp << in.rdbuf(); return temp.str(); } void localStream() { PersistStream ps("temp.tmp","Log File - temp.dat"); ps << "\n data from function localStream()"; } void main() { try { localStream(); PersistStream ps; ps << "\n A line from main"; ps << "\n a double from main: " << 3.1415927 << "\n\n"; std::cout << ps.say(); } catch(std::exception& e) { std::cout << "\n " << e.what() << "\n\n"; } }