I want to redirect std to a file.
To do this, I wrote a class Foo
, where I connect / disconnect the buffer in the writeToFilEnabled
.
However, there is Segmentation fault. How is it correct?
#include <iostream>
#include <fstream>
class Foo {
public:
Foo() {
out.open("out.txt");
coutbuf = std::cout.rdbuf();
}
void writeToFileEnabled(bool enabled) {
if (enabled)
std::cout.rdbuf(out.rdbuf());
else
std::cout.rdbuf(coutbuf);
}
void test(int a) {
std::cout << a << "\n";
}
private:
std::ofstream out;
std::streambuf * coutbuf;
};
int main()
{
Foo foo;
foo.test(1);
foo.test(2);
foo.writeToFileEnabled(true);
foo.test(3);
foo.test(4);
}