Custom streambuffer in std::ofstream

1.1k views Asked by At

I know that in std::ostream, I can use a custom streambuf through either stating so in the constructor:

std::ofstream temp;
temp.open("file.txt", std::ios_base::in);
std::ostream example(temp.rdbuf());

as well as by setting it afterwards (same first two lines as before, but change the last line to:

std::ostream example;
example.rdbuf(temp.rdbuf());

My question is: How can I do that in std::ofstream? I want to be able to overwrite the methods xsgetn and xsputn implemented in std::streambuf in my own custom class and use this in my ofstream, but, short of writing my own custom ofstream am unsure of how to do so.

1

There are 1 answers

0
David G On BEST ANSWER

The concrete file stream classes have their own rdbuf() method that takes 0 arguments and it hides the other rdbuf() method inherited from the virtual base std::basic_ios. Qualifying the name to lookup the base class method should work:

std::ofstream ofs;
ofs.basic_ios<char>::rdbuf(example.rdbuf());