mercredi 30 novembre 2016

Writing formatted output to two files at the same time

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 std::ostream& 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';

result 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!

Aucun commentaire:

Enregistrer un commentaire