Add custom function to ifstream

I would like my own class to work just like ifstream, but I can easily get the file size.

here is the title:

#include <fstream> using namespace std; class ifile: public ifstream { size_t _file_size = 0; size_t calculate_file_size(); public: ifile(): ifstream(), _file_size(0) {} ifile(const char *filename, ios_base::open_mode mode = ios_base::in): ifstream(filename, mode) { _file_size = cal_file_size(); } size_t get_file_size(); virtual ~ifile(); }; 

I found a lot of information that I should not inherit from ifstream. How then can I easily solve my problem?

Edit:

calculate_file_size:

 size_t ifile::calculate_file_size() { auto present_pos = tellg(); seekg(0, ifstream::end); auto file_size = tellg(); seekg(present_pos); return file_size; } 
  • It would be nice to see the right example (if I inherit from ifstream ).
  • The reason is to calculate once and read many times.
  • Why not get_file_size(ifstream &ifs) ? My ifstream obj is static, so it is evaluated many times.
+5
source share

Source: https://habr.com/ru/post/1270677/


All Articles