Alright so I am trying to swap fstreams. I do not use c++11 so there is no swap function. Is there anyway I can swap the files 2 fstreams have open? Or is there a way to get the name of the file that the fstream has open?

Define "swap" for your purpose. Do you want to swap the file references entirely or just copy the contents of one stream to another?

Or is there a way to get the name of the file that the fstream has open?

Nope. You need to save the name, which is easy by wrapping the whole shebang into another object that has two members: one for the stream and one for the file name.

I mean swap the file refrences. And in all reality I will be working with more than two files because I am working on an external polyphase sort. So a wrapper class would not help.

and with a polyphase sort i need to swap which file is the output file and will be changing the output file multiple times

And in all reality I will be working with more than two files because I am working on an external polyphase sort

Okay, you're making it too complicated. You'll already have a collection of stream objects for a polyphase sort, so just mark the index of (or have a reference to) the current output stream and update it as necessary. That's so much more intuitive than swapping streams left and right, even if you were using C++11.

If you cannot use the C++11 swap functions, your best bet is probably to use the filebufs directly and construct vanilla istream / ostream objects from them. Something like this:

class my_ofstream : public std::ostream {
  private:
    std::string filename;
    std::filebuf* pfb;
  public:
    my_ofstream(const std::string& aFilename) :
      std::ostream( new std::filebuf(aFilename.c_str()) ),
      filename(aFilename),
      pfb(static_cast<std::filebuf*>(std::ostream::rdbuf())) { };

    ~my_ofstream() {
      delete pfb;
    };

    void swap(my_ofstream& rhs) {
      using std::swap;
      swap(filename, rhs.filename);
      swap(pfb, rhs.pfb);
      this->rdbuf(pfb);
      rhs.rdbuf(rhs.pfb);
    };

    const std::string& get_filename() const {
      return filename;
    };
};

Another option is just to keep track of the filebuf objects instead of file-streams, and create temporary i/ostreams just when you need them.

EDIT: Deceptikon's solution is much better!

I don't think I quite understand Deceptikon's solution. could you give an example?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.