c++ - Difficulty overloading operator<< for file handling class -
i have to:
define
file_handleclass constructor takes string argument (file name), opens file in constructor, , closes in destructor.
as understand it, class used provide raii , trying implement class using file* basic data structure goal make file* smart pointer:
filehandler.h:
// class cfile_handler based on file* class cfile_handler { public: cfile_handler(); // default constructor cfile_handler(const std::string& filename, // constructor const std::string& mode); ~cfile_handler (); // destructor // modifying member function void open_file(const std::string& filename, const std::string& mode); protected: typedef file* ptr; private: cfile_handler(const cfile_handler&); // prevent copy creation cfile_handler& operator= (const cfile_handler&); // prevent copy assignment ptr c_style_stream; // data member }; filehandler.cpp:
// class cfile_handler member implementations // default constuctor cfile_handler::cfile_handler() { } // constructor cfile_handler::cfile_handler(const std::string& filename, const std::string& mode = "r") : c_style_stream( fopen( filename.c_str(), mode.c_str() ) ) { } // destructor cfile_handler::~cfile_handler() { if (c_style_stream) fclose(c_style_stream); } // modifying member functions void cfile_handler::open_file(const std::string& filename, const std::string& mode) { c_style_stream = ( fopen( filename.c_str(), mode.c_str() ) ); } however, i'm having difficulties in overloading i/o operators<< / >>, can't figure out how implement either of them.
how overload operator<< such class works iostream objects?
edit:
as proposed @lokiastari, better strategy inherit istream , define own streambuf.
could give example or directions implementation of streambuf handles file*?
what want provide is:
cfile_handler fh("filename.txt", "r"); std::string file_text; fh >> file_text; or:
cfile_handler fh("filename.txt", "w"); fh << "write file";
you can derive types of std::streams using std::streambuf handle file*
#include <iostream> #include <stdio.h> class outputfilepointerstream: public std::ostream { class outputfilepointerstreambuf: public std::streambuf { file* buffer; public: outputfilepointerstreambuf(std::string const& filename) { buffer = fopen(filename.c_str(), "w"); } ~outputfilepointerstreambuf() { fclose(buffer); } virtual std::streamsize xsputn(const char* s, std::streamsize n) override { static char format[30]; sprintf(format, "%%.%lds", n); fprintf(buffer, format, s); return n; } }; outputfilepointerstreambuf buffer; public: outputfilepointerstream(std::string const& filename) : std::ostream(nullptr) , buffer(filename) { rdbuf(&buffer); } }; int main() { outputfilepointerstream filestream("test"); filestream << "testing: " << 5 << "><\n"; filestream << "line again\n"; }
Comments
Post a Comment