0

For an assignment I have to write a class that offers the same facilities as ostream, but outputs to two files at the same time.

Currently I have the following code (in-class implementations for brevity):

#ifndef BISTREAM_H_
#define BISTREAM_H_

#include <iostream>
#include <fstream>

class BiStream : public std::ostream
{
    std::ofstream d_firstFile;
    std::ofstream d_secondFile;
    public:
        BiStream(std::ofstream& one, std::ofstream& two)
        :
            d_firstFile(std::move(one)),
            d_secondFile(std::move(two)) 
        {}
        friend BiStream& operator<<(BiStream& out, char const *txt)
        {
            out.d_firstFile << txt;
            out.d_secondFile << txt;
            return out;
        }
};
#endif

Then I can use this in the following way:

#include "bistream.h"

using namespace std;

int main()
{
    ofstream one("one");
    ofstream two("two");

    BiStream ms(one, two);

    ms << "Hello World" << endl;    // Write to files and flush stream
}

If I run the resulting program, it correctly prints "Hello World" to both files, but no newline is added to either files.

Furthermore, statements like (after including iomanip of course)

ms << std::hex << 5 << '\n';

results in no text printed in the files. As a last example:

ms << "test" <<"Hello World" << endl;  

Only prints "test" to the files. This all implies that my overload insertion operator only writes the first argument to the file...

What is the best way to approach this problem? The exercise hints at a second class that inherits from std::streambuf, but std::streambuf is something that I don't understand and searching for explanations on the internet hasn't made it any clearer.

Thanks!

Nigel Overmars
  • 213
  • 2
  • 11
  • The right way to do it is to implement a class derived from `std::streambuf`, then simply wrap an `ostream` around it. Let the `ostream` deal with formatting; `streambuf` is a lower-level interface, working with a stream of bytes. See how, for example, `std::basic_ofstream` doesn't re-implement any `operator<<`; it just constructs its base class with an instance of `std::basic_filebuf`. The latter does all the file-specific work. – Igor Tandetnik Nov 30 '16 at 22:26
  • 1
    The return type of the `operator<<` function needs to be `BiStream &`. – R Sahu Nov 30 '16 at 22:31

0 Answers0