How to extend ifstream?

97 Views Asked by At

I would like to extend ifstream by defining a new class ifstreamExt where :

  1. there is a class variable called 'directory' that is a string and that holds the location where the file will be opened.

  2. the open method is redefined so to use the directory variable.

  3. and finally, >> is supposed to work with string at least.

I managed to do 1 & 2 - but I am failing with 3. I do not know how to write it, I made multiple trials. The first one was using getline, it worked fine, but not as >> works ; this operator skips blanks and retrieve consecutive non-blanks character, whereas getline gets the full line and does not pick each of sub-string.

class ifstreamExt : ifstream {
  public:

    void open(string f) {
      string s = h + "/" + f;
      name = s;
      if (!is_open()) {
        cerr << "cannot open " << s << endl;
        exit(1);
      } else {
        cerr << "open file " << s << endl;
      }
    }
    friend ifstreamExt & operator >> (ifstreamExt & is, string &str) {
    }

    static void set_directory(string d) {
      cerr << "set home directory : " << d << endl;
      h = d;
      DIR* dir = opendir(h.c_str());
      if (dir) {
        cerr << "directory " << h << " exists " << endl;
      } else {
        cerr << "directory " << h << " does not exist " << endl;
        exit(1);
      }
    }
  private :
    static string h;
};
1

There are 1 best solutions below

1
Pierre G. On

Following the recommendations posted in the comments, here is ifstreamExt which is a new class with composition. Any feedback welcome !

class ifstreamExt {
  public :
    ifstreamExt() : file_() { }
    void open(const std::string &filename) {
      string f_name = _dir_ + "/" + filename;
      file_.open(f_name);
      if (!file_.is_open()) {
        cerr << "cannot open " << f_name << endl;
        exit(1);
      } else {
        cerr << "open " << f_name << endl;
      }
    }
    void close(void) {file_.close();}
    bool is_open() {return file_.is_open();}

    friend ifstreamExt& operator >> (ifstreamExt & is, string &str) {
      is.file_ >> str;
      return is;
    }
    static void set_directory(string d) {
      _dir_ = d;
    }
  private:
    std::ifstream file_;
    static string _dir_;

};