Trying to override streambuf to use with cout

Hi,

I'm trying to grab all the input sent to cout to modify and redirect it. I used the example from http://www.dreamincode.net/code/snippet2499.htm, which works fine using the following code:

1
2
3
4
5
    std::ofstream file_sink("encrypted.bin", std::ios_base::binary | std::ios_base::out);
    basic_xor_filter<char> filter(*(file_sink.rdbuf()), 0x7F);
    std::ostream output_stream(&filter);
    output_stream << "Hello World" << std::endl;
    output_stream.flush();


The basic_xor_filter class overrides streambuf and simply XORs the input characters before sending them to the provided streambuf (in this case, a file). My problem occurs when I try setting cout's rdbuf() to filter:

1
2
3
    streambuf* s = &filter;
    cout.rdbuf( s );
    cout << "Hello World\n";


This code causes a glibc "double free or corruption (!prev)" error. Could anyone tell me where I am going wrong? Perhaps I just don't understand the concepts properly?

Thanks very much.
can you not use streambuf s(&filter); ?
Thanks for the reply Zaita. Unfortunatley that doesn't work, I get a "no matching function call" error. I also tried streambuf s( &((streambuf)filter) );, but to no avail. Does anyone else have any ideas as to why this doesn't work? Has anyone else managed to do this kind of thing with cout?
Why not just send it to a strstream?
I'm not quite sure how a strstream will help me, but I'm not that experienced with C++ streams, could you explain how? I should point out that my aim is not to actually send the stream to a file, I'm just trying it as an example so that I can manipulate the streams for my program.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <string>
#include <iostream>
#include <strstream>

using namespace std;

int main() {
  streambuf*     sCoutBackup;
  strstream      myString;
  sCoutBackup    = cout.rdbuf();

  cout.rdbuf(myString.rdbuf());
  myString << "some text" << endl;
  cout.rdbuf(sCoutBackup);
  cout << myString.str();

  return 0;
}


Note: This seems to bug on my system by adding some extra crap during the cout at the end. NFI why, but you can see if it does the same on your system.
Thanks Zaita, that way makes a lot more sense! Although I'm guessing line 13 should have been myString << "some text" << endl;. The only problem now is that I also get the random crap after the string is printed.
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <string>
#include <iostream>
#include <strstream>

using namespace std;

int main() {
  streambuf*     sCoutBackup;
  strstream      myString;
  sCoutBackup    = cout.rdbuf();

  cout.rdbuf(myString.rdbuf());
  myString << "some text" << endl;
  cout.rdbuf(sCoutBackup);

  myString << '\0';
  cout << myString.str();

  return 0;
}
Thanks Zaita!
Topic archived. No new replies allowed.