Add own function to ifstream

Viewed 269

I would like to have my own class that work exactly like ifstream in any case but I can easily get the size of a file.

here is header:

#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 have found many many information that I should not inherit from ifstream. How then I can easy resolve my problem then?

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;
}
  1. It would be nice to see proper example (if I can inherit from ifstream).
  2. The reason is to calculate once and read many times.
  3. Why not get_file_size(ifstream &ifs)? My ifstream obj is static this is so it's calculated many times.
1 Answers
Related